4dummies
4dummies

Reputation: 819

How to find the name of the current function?

I know it seems lame, but I'd like to have a function get access to its own name for printing error or debugging messages. It would be easy then to have a standard way to start the printout:

print(__myname__,"is reporting the following..."

I prefer this to having to explicitly type the name each time because I often want to cut and paste such things, and I'd like any name change to be automatic, and thus more robustly correct.

This is similar to another question but I want the name of the current function, not the name of its caller.

I note that the special name

__name__

in this spot is reporting the name of the package, not the name of the function.

Upvotes: 2

Views: 136

Answers (1)

zch
zch

Reputation: 15278

You can use traceback module to extract stack information:

import traceback

def current_function_name():
    return traceback.extract_stack()[-2][2]    

def foo():
    print current_function_name()

>>> foo()
foo

Upvotes: 4

Related Questions