getting name of the function you're in
Richard Townsend
richard at NOstarfighterSPAM.freeuk.com
Wed May 15 13:55:46 EDT 2002
"Bob Purvy" <bpurvy at packeteer.com> wrote in message
news:3CE295FF.2020202 at packeteer.com...
> does anyone know how to do this? I asked our resident Python guru and
> he didn't know. Also searched the docs reasonably thoroughly.
>
> it's for logging debug info to a custom log file.
>
> (I should mention that currently I'm on 2.0. Will move to 2.2 shortly,
> so a 2.2-only answer is still useful.)
>
I don't know if there is an easier way, but this works for me:
import sys
def my_func():
# Raise an exception so we can get a traceback
try:
raise ZeroDivisionError
except ZeroDivisionError:
# Get the traceback object
tb = sys.exc_info()[2]
# Get the stack frame object for this function
f = tb.tb_frame
# Get the code object from the frame object
co = f.f_code
# Get the module and function
# names from the code object
module_name = co.co_filename
function_name = co.co_name
print module_name, function_name
if __name__ == '__main__':
my_func()
If you move the functionality into its own function, you can use the stack
frame object's f_back attribute to navigate to previous stack frame.
More information about the Python-list
mailing list