Python classes: how to find the name of (potential) parent class?

Mike C. Fletcher mcfletch at rogers.com
Sat Nov 30 12:59:10 EST 2002


Here's a simple function that should point you in the right direction. 
 Note that type(c) == types.ClassType for "classic" Python classes, but 
not for new-style classes in Python 2.2+, this code uses that to allow 
shortcutting the finding of bases for new-style classes.

Enjoy,
Mike

import types
def parents( c, seen=None ):
    """Python class base-finder"""
    if type( c ) == types.ClassType:
        if seen is None:
            seen = {}
        seen[c] = None
        items = [c]
        for base in c.__bases__:
            if not seen.has_key(base):
                items.extend( parents(base, seen))
        return items
    else:
        return list(c.__mro__)

class A:
    pass
class B(A):
    pass
class C(A):
    pass
class D(B,C,A):
    pass
class E(A,C,D):
    pass
class F(E):
    pass

print 'Classic classes'
print parents(A)
print parents(B)
print parents(C)
print parents(D)
print parents(E)
print parents(F)


class A(object):
    pass
class B(A):
    pass
class C(A):
    pass
class D(B,C,A):
    pass
class E(A,C,D):
    pass
class F(E):
    pass

print 'Now new-style classes'
print parents(A)
print parents(B)
print parents(C)
print parents(D)
print parents(E)
print parents(F)


Pierre Rouleau wrote:

> Is it possible to find, at run time, what are the parent class of a 
> given Python class?
>
_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/







More information about the Python-list mailing list