In Python, without using the traceback
module, is there a way to determine a function's name from within that function?
Say I have a module foo
with a function bar
. When executing foo.bar()
, is there a way for bar
to know bar
's name? Or better yet, foo.bar
's name?
#foo.py def bar(): print "my name is", __myname__ # <== how do I calculate this at runtime?
It's this method object that has the __func__ attribute, which is just a reference to the wrapped function. By accessing the underlying function instead of calling the method, you remove the typecheck, and you can pass in anything you want as the first argument.
Use the __name__ Property to Get the Function Name in Python In Python, every single function that is declared and imported in your project will have the __name__ property, which you can directly access from the function.
Keyword def that marks the start of the function header. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. Parameters (arguments) through which we pass values to a function. They are optional.
import inspect def foo(): print(inspect.stack()[0][3]) print(inspect.stack()[1][3]) # will give the caller of foos name, if something called foo foo()
output:
foo <module_caller_of_foo>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With