Is there a way to determine a function's name from within the function?
def foo():
print("my name is", __myname__) # <== how do I calculate this at runtime?
In the example above, the body of foo
will somehow access the function name "foo"
without hard-coding it. The output would be:
>>> foo()
my name is foo
If you don't want to play with the stack yourself, you should either use "bar"
or bar.__name__
depending on context.
Python doesn't have a feature to access the function or its name within the function itself. A magic __function__
had been proposed for Python 3.0 but rejected. See PEP 3130 – Access to Current Module/Class/Function.
The given rejection notice is:
This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.