why is this so slow?

Lowell Kirsh lkirsh at cs.ubc.ca
Thu Sep 2 06:56:40 CEST 2004


thanks for the help. the link is really good too :)

Robert Brewer wrote:

> Lowell Kirsh wrote:
> 
>>I created the following class (I know it's a dirty hack) so I 
>>could do 
>>foo.bar instead of using a dictionary and having to type foo['bar'] :
>>
>>     class DefaultAttr(object):
>>         def __getattribute__(self, attr):
>>             if not hasattr(self, attr):
>>                 return ''
>>             return object.__getattribute__(self,attr)
>>
>>but its use is totally slowing down my program. Why is it so 
>>slow and is there a better way?
> 
> 
> IIRC, hasattr calls __getattribute__. If you run:
> 
>      class DefaultAttr(object):
>          def __getattribute__(self, attr):
>              print "Looking up %s" % attr
>              if not hasattr(self, attr):
>                  return ''
>              return object.__getattribute__(self,attr)
>      da = DefaultAttr()
>      print da.f
> 
> ...you can see the lookups whizzing by. Try this instead:
> 
> class DefaultAttr(object):
>     def __getattr__(self, attr):
>         return ''
> 
> http://docs.python.org/ref/attribute-access.html explains the
> difference, that __getattr__ only gets called when the object is not
> found "in the usual places".
> 
> 
> HTH
> 
> Robert Brewer
> MIS
> Amor Ministries
> fumanchu at amor.org



More information about the Python-list mailing list