where am I ?
skip at pobox.com
Wed Mar 12 22:30:17 CET 2003
Michele> I would like to define a function 'whereami' that returns
Michele> information about the scope where it is called.
In addition to the information Jeremy gave you about sys._getframe(), take a
look at traceback.print_stack() and traceback.extract_stack():
Help on function print_stack:
print_stack(f=None, limit=None, file=None)
Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
Help on function extract_stack:
Extract the raw traceback from the current stack frame.
The return value has the same format as for extract_tb(). The
optional 'f' and 'limit' arguments have the same meaning as for
print_stack(). Each item in the list is a quadruple (filename,
line number, function name, text), and the entries are in order
from oldest to newest stack frame.
>>> def f():
... return whereami()
>>> def whereami():
... return traceback.extract_stack()
[('<stdin>', 1, '?', None), ('<stdin>', 2, 'f', None), ('<stdin>', 2, 'whereami', None)]
More information about the Python-list