Inefficiency of __getattr__
Huaiyu Zhu
hzhu at yahoo.com
Sun Oct 1 00:07:51 EDT 2000
Is __getattr__ supposed to be run only when the attribute is not already
defined? This does not seem to be so and it is very costly (equivalent of
addition of two 1000 element vectors). In the following example __getattr__
should not be invoked even if it is there:
======================== test program ===========================
class A:
def __add__(self, other): pass
def __getattr__(self, name):
try: return self.__dict__[name]
except KeyError: raise AttributeError, name
a = A()
def test():
for i in xrange(10000): a+a
from profile import run
run("test()")
==================================================================
Result with __getattr__ defined:
20003 function calls (10004 primitive calls) in 1.870 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.870 1.870 <string>:1(?)
0 0.000 0.000 profile:0(profiler)
1 0.000 0.000 1.870 1.870 profile:0(test())
10000 0.220 0.000 0.220 0.000 test_getattr.py:2(__add__)
10000/1 1.650 0.000 1.870 1.870 test_getattr.py:3(__getattr__)
1 0.000 0.000 1.870 1.870 test_getattr.py:8(test)
==================================================================
Result with __getattr__ commented out:
10003 function calls in 0.560 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.530 0.530 <string>:1(?)
0 0.000 0.000 profile:0(profiler)
1 0.030 0.030 0.560 0.560 profile:0(test())
10000 0.170 0.000 0.170 0.000 test_getattr.py:2(__add__)
1 0.360 0.360 0.530 0.530 test_getattr.py:8(test)
--
Huaiyu Zhu hzhu at users.sourceforge.net
More information about the Python-list
mailing list