2

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.

4dummies
  • 759
  • 2
  • 9
  • 22
  • @mypetlion this does not look like a proper duplicate, because the OP wants to find the name of the currently executed function without referring to it explicitly. – bereal Sep 24 '18 at 22:23
  • 1
    Possible duplicate of [How to get the caller's method name in the called method?](https://stackoverflow.com/questions/2654113/how-to-get-the-callers-method-name-in-the-called-method) – codeforester Sep 24 '18 at 22:31

1 Answers1

4

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
zch
  • 14,931
  • 2
  • 41
  • 49