why is this so slow?

Robert Brewer fumanchu at amor.org
Thu Sep 2 00:25:21 EDT 2004


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