【问题标题】:Python 3.5 Type Hinting Factory TypePython 3.5 类型提示工厂类型
【发布时间】:2016-05-24 00:14:44
【问题描述】:

如果我使用 boto3 创建到 aws-ec2 的连接,它的返回类型为 boto3.resources.factory.ec2.ServiceResource

import boto3
cnxn = boto3.Session().resource('ec2')
type(cnxn)
>>  boto3.resources.factory.ec2.ServiceResource

我希望能够将其用作类型提示的类型。但是,如果我尝试引用它,则会出现错误。

boto3.resources.factory.ec2.ServiceResource
AttributeError: module 'boto3.resources.factory' has no attribute 'ec2'

有没有办法将这些类型用作提示?

编辑:导入也不起作用

import boto3.resources.factory.ec2
>> ImportError: No module named 'boto3.resources.factory.ec2'; 'boto3.resources.factory' is not a package

【问题讨论】:

  • 也许你需要做import boto3.resources.factory.ec2
  • 这给出了 ImportError - 请参阅编辑。
  • import boto3.ec2 怎么样(如this question 中的建议)?如果你用谷歌搜索那个 AttributeError 消息,你会发现人们遇到类似错误的各种页面;其中一些可能会对您有所帮助。
  • 说明你为什么要“引用”该类型?您不能引用类型。即使要知道变量是否属于特定类型,我也只是使用表达式。

标签: python amazon-ec2 python-3.5 boto3


【解决方案1】:

您需要使用forward references,因为这些类型在运行时才存在。

【讨论】:

    【解决方案2】:

    请参考pythontype documentation

    你得到的是一个类型对象。如果您的意图是从该类型中创建一个新对象,则使用class type(name, bases, dict) 创建一个新对象。如示例中所示:

    >>> class X(object):
    ...     a = 1
    ...
    >>> X = type('X', (object,), dict(a=1))
    

    【讨论】:

      猜你喜欢
      • 2013-07-14
      • 2015-10-17
      • 2016-12-06
      • 2015-12-10
      • 2017-12-03
      相关资源
      最近更新 更多