isinstance and issubclass in Python

isinstance

Use this built-in function to find out if a given object is an instance of a certain class or any of its subclasses. You can even pass a tuple of classes to be checked for the object.

The only gotcha you will discover is this: in Python a bool object is an instance of int! Yes, not kidding!

issubclass

This built-in function is similar to isinstance, but to check if a type is an instance of a class or any of its subclasses.

Again, the only gotcha is that bool type is subclass of int type.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s