Do deep inheritance trees degrade efficiency?

Chris Rebert clp2 at rebertia.com
Thu Mar 19 05:13:48 EDT 2009


On Wed, Mar 18, 2009 at 6:09 AM, Anthra Norell <anthra.norell at bluewin.ch> wrote:
> Would anyone who knows the inner workings volunteer to clarify whether or
> not every additional derivation of a class hierarchy adds an indirection to
> the base class's method calls and attribute read-writes. In C++, I suppose,
> a three-level inheritance would resolve into something like
> *(*(*(*(base_class_method ())))).

There's no effect on attribute read-writes as they all take place
within the single __dict__ of the instance. As for method lookup, it
doesn't add an indirection per se, but rather the list of classes to
look thru to find a method gets longer, making base-class method
lookups slower. IIRC, a typical method lookup does something like the
following pseudocode:

for klass in the_object.__mro__:
    if method_name in klass.__dict__:
        return klass.__dict__[method_name]
raise AttributeError # no such attribute

The __mro__ being the Method Resolution Order, a list containing
the_object's class and that class' superclasses. __dict__ is the
namespace dictionary of an individual class.

However, you shouldn't really worry about the inefficiency of a deep
inheritance tree as Python's dictionary implementation (used for
namespace lookup) is super-optimized, and in any case the inefficiency
ought to be negligible compared to the actual work done in the program
(if it's not, there's something wrong with how the program has been
coded).

[Note: I'm purposefully ignoring the fact that methods and attributes
are in reality looked up in the exact same way for
simplicity/clarity.]

Cheers,
Chris

-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-list mailing list