0

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
>>>
shepster
  • 339
  • 3
  • 13
  • Does this answer your question? https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python – gshpychka Aug 17 '21 at 21:15
  • Hmmm... Nice detailed article! First pass didn't seem to help. All the type checking is for the standard types. – shepster Aug 17 '21 at 21:24
  • It looks like `isinstance(ec2, object)` will work, but I was hoping for a check that is a little more granular, that delves into the type of the object. – shepster Aug 17 '21 at 21:25
  • The type of the object in your example is `botocore.client.EC2` – gshpychka Aug 17 '21 at 21:26
  • Neither `if type(ec2) == 'botocore.client.EC2':` or `if type(ec2) == botocore.client.EC2:` are valid statements. Substituting 'is' for '==' doesn't work either. – shepster Aug 17 '21 at 21:30
  • The latter is indeed a valid statement - you just need to import the appropriate module first. – gshpychka Aug 17 '21 at 21:32
  • What's the underlying reason to need to query the type of this object? Maybe there's a better way to solve what you're trying to do. – jarmod Feb 18 '22 at 15:48

1 Answers1

0

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