【问题标题】:Validating Type or Class of EC2 Object验证 EC2 对象的类型或类别
【发布时间】:2022-02-18 23:45:59
【问题描述】:

我想验证 boto3 客户端对象的类型或类。

>>> import boto3
>>> ec2 = boto3.client('ec2')
>>> type(ec2)
<class 'botocore.client.EC2'>
>>>

这如何转化为我可以用于if 比较的东西? if type(ec2) == 'botocore.client.EC2':if isinstance(ec2, botocore.client.EC2): 之类的语句不起作用。

@gshpychka 说我需要先导入相应的模块。所以我需要 botocore 模块?似乎仍然无法正常工作。

>>> import boto3
>>> import botocore
>>> ec2 = boto3.client('ec2')
>>> type(ec2)
<class 'botocore.client.EC2'>
>>> type(ec2) == botocore.client.EC2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'botocore.client' has no attribute 'EC2'
>>> type(ec2) == botocore.client
False
>>> type(ec2) == botocore
False
>>>

【问题讨论】:

  • 这能回答你的问题吗? stackoverflow.com/questions/152580/…
  • 嗯...好详细的文章!第一次通过似乎没有帮助。所有类型检查都是针对标准类型的。
  • 看起来isinstance(ec2, object) 可以工作,但我希望能进行更细粒度的检查,深入研究对象的类型。
  • 你的例子中对象的类型是botocore.client.EC2
  • if type(ec2) == 'botocore.client.EC2':if type(ec2) == botocore.client.EC2: 都不是有效的语句。用 'is' 代替 '==' 也不起作用。

标签: python amazon-web-services boto3 botocore


【解决方案1】:

问题是隐式的 EC2 类创建: https://github.com/boto/botocore/blob/develop/botocore/client.py#L111

在我看来,这里没有漂亮的选择,但你可以使用这样的东西:

>>> print(ec2.__module__ + '.' + ec2.__class__.__name__ == "botocore.client.EC2")
True

>>> print(ec2.__class__.__name__ == "EC2")
True

【讨论】:

    猜你喜欢
    • 2021-05-17
    • 2017-03-16
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2022-01-10
    • 2013-12-12
    相关资源
    最近更新 更多