How to get the parents of a Python class?

If you want all the ancestors rather than just the immediate ones, use inspect.getmro:

import inspect
print inspect.getmro(cls)

Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).


Use the following attribute:

cls.__bases__

From the docs:

The tuple of base classes of a class object.

Example:

>>> str.__bases__
(<type 'basestring'>,)

Another example:

>>> class A(object):
...   pass
... 
>>> class B(object):
...   pass
... 
>>> class C(A, B):
...   pass
... 
>>> C.__bases__
(<class '__main__.A'>, <class '__main__.B'>)

The fastest way to get all parents, and in order, is to just use the __mro__ built-in.

For instance, repr(YOUR_CLASS.__mro__).

The following:

import getpass
getpass.GetPassWarning.__mro__

...outputs, in order:

(<class 'getpass.GetPassWarning'>, <type 'exceptions.UserWarning'>, <type 'exceptions.Warning'>, <type 'exceptions.Exception'>, <type 'exceptions.BaseException'>, <type 'object'>)

There you have it. The "best" answer may have more votes but this is so much simpler than some convoluted for loop, looking into __bases__ one class at a time, not to mention when a class extends two or more parent classes. Importing and using inspect just clouds the scope unnecessarily.

Tags:

Python

Oop