where am I ?

Geoff Gerrietts geoff at gerrietts.net
Wed Mar 12 22:23:07 CET 2003

Quoting Michele Simionato (mis6 at pitt.edu):
> I would like to define a function 'whereami' that returns information
> about the scope where it is called. For instance if I call 'whereami'
> inside a function f, it should give me f, if I call 'whereami' inside a class
> C, it should give me the class C, etc.
> whereami()  #=> __main__
> def f():
>     whereami() #=> f
> class C:       #=> C
>     whereami()
> My guess is that I need to raise an exception and follow the traceback,
> but I am not familiar with this kind of tricks. Any help ?

If you use the traceback module, you can peer back into the stack
regardless of whether there's an exception. I use a similar trick in a
logging routine:

  file, line, func, txt = traceback.extract_stack(None,2)[0]

That returns my current function's caller.

If you want your current function, try:

  file, line, func, txt = traceback.extract_stack(None,1)[0]


Geoff Gerrietts        <geoff at gerrietts dot net>
"Ordinarily he was insane, but he had lucid moments 
when he was merely stupid."        --Heinrich Heine

More information about the Python-list mailing list