Friday, June 25, 2010

Python Is Descendant

How do you check if a given Python object is a descendant of a given class? Here is a good way to do it using the inspect.getmro() function. This function returns a list of all the object's base classes, including all grand-parent classes, and so on, all the way up the class hierarchy.

Here is my version of the technique put into a simple function that will test if the specified object is a descendant of the specified class name.
from inspect import getmro

def istype(obj, typename):
return typename in [clsobj.__name__ for clsobj in getmro(obj.__class__)]

class A(object):
pass

class B(A):
pass

if __name__ == "__main__":
print istype(B(), "A")
print istype(B(), "object")