blog.camball.io

Python

A Common Type Checking Fallacy in Python

By Cameron Ball

Learn when to use `is` versus `isinstance` in Python when comparing types.

Take a look at the following code evaluations:

>>> class MyError(IndexError):
...     pass
...
>>> e = MyError()
>>> type(e)
<class '__main__.MyError'>
>>> isinstance(e, MyError)
True
>>> isinstance(e, IndexError)
True
>>> type(e) is MyError
True
>>> type(e) is IndexError
False

As you can see, is only checks whether the exact type is the same, whereas isinstance() will also check for subclasses of a type.

This isn’t a bad thing—just be aware of which you intend to use… and in the vast majority of cases, isinstance() is probably the one you intend to use.