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.

2
  • @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. Commented Sep 24, 2018 at 22:23
  • 1
    Possible duplicate of How to get the caller's method name in the called method? Commented Sep 24, 2018 at 22:31

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

It's going to be way more expensive than a string literal, though.
Since it's for debugging, I don't much care.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.