profile problem

Rick White rlw at stsci.edu
Thu May 25 22:16:18 CEST 2000


I have encountered a problem with the profiler.  Here's a brief
demonstration:

Python 1.5.2 (#2, Apr 17 1999, 11:16:17) [C] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> class Test:
...     def __getattr__(self,attr): raise AttributeError
...  
>>> def g():
...     def f():
...         if hasattr(Test(),'x'): pass
...     f()
...     time.sleep(1)
... 
>>> import time, profile
>>> profile.Profile(time.time).run('g()').print_stats()

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.992    0.992 <stdin>:1(g)
        1    0.992    0.992    0.992    0.992 <stdin>:2(f)

Profile erroneously assigns all the execution time to function f()
rather
than to g() where it belongs.  If I replace f() with a function that
does
not call hasattr, but instead just tries to access the attribute and
catches the AttributeError, it works correctly.

The problem seems to be that the exception raised in __getattr__ (in
Python) is caught by the hasattr function (in C code).  As a result the
profile stack gets out of sync with the real program stack, and the
accounting goes awry.  Things work correctly as long as the exception is
both raised and caught within Python code.  I looked at the profile
module
and was able to identify the cause (in a much more complicated program),
but so far I haven't figured out how to fix it.  Any suggestions?

- Rick

-- 
Richard L. White    rlw at stsci.edu    http://sundog.stsci.edu/rick/
Space Telescope Science Institute
Baltimore, MD



More information about the Python-list mailing list