Here's a quick hack to help when you're lost in a too-large Python inheritance tree. What class provides the most specific implementation of a method or attribute?

def find(cls, name):
    for sup in cls.mro():
        if name in sup.__dict__:
            return sup.__name__
    return None

def find_all_vars(cls):
    for name in sorted(dir(cls)):
        where = find(cls, name)
        print "%s.%s" % (where, name)


def find_all_methods(cls):
    for name in sorted(dir(cls)):
        if callable(getattr(cls, name)):
            where = find(cls, name)
            print "%s.%s" % (where, name)

Example usage:

class Foo(object):
    def bar(self): pass
    def fleem(self): pass

class Bar(Foo):
    def bar(self): pass

class Baz(Bar):
    def flarf(self): pass

find_all_methods(Baz)

Output:

object.__class__
object.__delattr__
object.__format__
object.__getattribute__
object.__hash__
object.__init__
object.__new__
object.__reduce__
object.__reduce_ex__
object.__repr__
object.__setattr__
object.__sizeof__
object.__str__
object.__subclasshook__
Bar.bar
Baz.flarf
Foo.fleem

Comments

comments powered by Disqus