"parent" in a class __init__ def?

bruno at modulix onurb at xiludom.gro
Tue Jun 13 04:55:19 EDT 2006


akameswaran at gmail.com wrote:
> bruno at modulix wrote:
> 
>>akameswaran at gmail.com wrote:
>>
>>> Intuitively, the name lookup on
>>>self.parent.foo would be faster than if you passed in the object in
>>>question
>>
>>
>>Each dot means doing a lookup in a namespace. The more dots, the more
>>lookups. And lookups do have a cost.
> 
> hmm, intuition may not be right in this case.

> Lookups do have a cost - now I"m almost tempted to write and run a test
> for this - but the cost of each lookup is also relative to the current
> scope. 

A common "optimization" trick is to 'localize' references before a heavy
loop, to avoid lookup cost, ie:

def method(self, *args):
  dothis = self.dothis
  dothat = somemodule.somefunc
  CONST = othermodule.CONST
  # heavy processing loop here


> I haven't looked over the implementation of the python
> interpreter - but I would hope the lookup on self would be optimized
> and trivial.

It's certainly not trivial. Must take into account instance attributes
(in __dict__ or __slots__), class attributes, inherited attributes,
overriding descriptors, non-overriding descriptors, __getattr__,  etc...
The incredible felxibility of Python's object model comes with a cost.

>  The next relevant question would be is it cheaper to
> lookup self.parent or to look up a method variable, 

The second - cf above.

> which I supsect
> would depend on the number of names in self vs. number of names in the
> method.

Namespaces are mostly built upon hashtables, so the number of names
should be mostly irrelevant.


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list