Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine function name from within that function (without using traceback)

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? 
like image 829
Rob Avatar asked Feb 21 '11 15:02

Rob


People also ask

What is __ func __ in Python?

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.

How do you read a function name in Python?

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.

What is @function name in Python?

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.


1 Answers

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> 
like image 81
Andreas Jung Avatar answered Sep 21 '22 13:09

Andreas Jung