python quickie : retrace function steps?

Alex Martelli aleax at
Wed Aug 20 19:04:13 CEST 2003

Matt Smith wrote:

> hi all,
> If I was to make a function call another function, and from that
> function, call another function (so that now I was in a 3rd function)
> something like this:
> (function 1)
>      |________(function 2)
>                     |________(function 3)
> Is there away I can print out the path my Program had taken (i want to
> do this as part of my error checking, so a user would always know the
> path my program took)?

Yes, the _getframe function of module sys exists essentially for this
purpose.  The leading underscore is meant to indicate you should not
use it for "production" purposes, but debugging uses are just fine.

> i.e. printted output of error would be:
>             error with function 3
>               function 3 called from function 2
>               function 2 called from function 1

Note, in particular, that the tracebacks that Python normally
produces if you raise exceptions have much the same information,
just with many more details (lines-within-functions, not just
function names).  You might prefer to work with the traceback
objects rather than (essentially) rebuild them yourself with

> In perl there is a function called CALLER, which I have used to the
> same effect, i was wondering if python had something similar for this?

Yes, you can see sys._getframe(N) as an equivalent to &caller($N).
sys._getframe returns a frame object, and the x.f_code.co_name
attribute (calling x the object in question) is the one you want.


More information about the Python-list mailing list