'Validating Type or Class of EC2 Object

I would like to validate the type or class of a boto3 client object.

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

How does that translate back into something I can use for an if comparison? Statements like if type(ec2) == 'botocore.client.EC2': and if isinstance(ec2, botocore.client.EC2): don't work.

@gshpychka says I need to import the appropriate module first. So I need the botocore module? Still doesn't seem to be working.

>>> 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
>>>


Solution 1:[1]

The problem is implicit EC2 class creation: https://github.com/boto/botocore/blob/develop/botocore/client.py#L111

It seems to me that there is no pretty option here, but you can use something like this:

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

or

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ddzgoev