Speed of attribute lookup (was Re: advice on programming style: is multiple inheritance bad?)

John Roth newsgroups at jhrothjr.com
Mon Feb 2 09:59:40 EST 2004


"Aahz" <aahz at pythoncraft.com> wrote in message
news:bvkh00$38r$1 at panix1.panix.com...
> In article <101rd69b9127s51 at news.supernews.com>,
> John Roth <newsgroups at jhrothjr.com> wrote:
> >"Joe Mason" <joe at notcharles.ca> wrote in message
> >news:slrnc1r2id.ea6.joe at gate.notcharles.ca...
> >>
> >> When profiling a large app at work, we discovered that in C++ accessing
> >> every parent class after the first is quite slow.  We were able to just
> >> flip the order of inheritance for some classes, but if you're planning
a
> >> complex use of multiple inheritance you should keep that in mind.  (I'm
> >> just assuming it has the same effect in Python.)
> >
> >Actually, it doesn't. For new style classes, Python precomputes the
> >method resolution order, so looking up a method is simply flipping
> >through a list of dictionaries until it finds the right one. It's
> >basically O(n) in the number of classes in the hierarchy.
> >
> >Given that you can add or remove attributes from any class at any time,
> >it's hard to see how it could be any faster.
>
> Actually, it's easy to see how it could be faster:

> The problem with attribute lookup in new-style classes is that any
> instance attribute could be a property.  So if Python finds an attribute
> on the instance, it needs to traverse the MRO to check if there's a
> property.  If there isn't one, that's an expensive waste.

I thought about that when new style classes came out, and managed
to convince myself that it couldn't happen, at least with data
properties. Unless trying to set the *same* attribute from the
setter invoked from the property actually works? That seems like
a lot of work to make it function poorly.

John Roth

> -- 
> Aahz (aahz at pythoncraft.com)           <*>
http://www.pythoncraft.com/
>
> "The joy of coding Python should be in seeing short, concise, readable
> classes that express a lot of action in a small amount of clear code -- 
> not in reams of trivial code that bores the reader to death."  --GvR





More information about the Python-list mailing list