How to get function name as string in Python?

Possible duplicate:
How to get function name as string in Python?

I know I can do this:

def func_name(): print func_name.__name__ 

which will return the function name as "my_func".

But as I enter the function, is there a way to directly name it in general? Sort of:

 def func_name(): print self.__name__ 

How will Python understand that I want the top of my code hierarchy?

+6
source share
4 answers

AFAIK, no. In addition, even your first method is not completely reliable, since a function object can have several names:

 In [8]: def f(): pass ...: In [9]: g = f In [10]: f.__name__ Out[10]: 'f' In [11]: g.__name__ Out[11]: 'f' 
+5
source

Not in general, but you can use validation

 import inspect def callee(): return inspect.getouterframes(inspect.currentframe())[1][1:4][2] def my_func(): print callee() // string my_func 

Source http://code.activestate.com/recipes/576925-caller-and-callee/

+9
source

You can also use the traceback module:

 import traceback def test(): stack = traceback.extract_stack() print stack[len(stack)-1][2] if __name__ == "__main__": test() 
+5
source

One possible way would be to use Decorators :

 def print_name(func, *args, **kwargs): def f(*args, **kwargs): print func.__name__ return func(*args, **kwargs) return f @print_name def funky(): print "Hello" funky() # Prints: # # funky # Hello 

The problem with this is that you will be able to print the name of the function before or after calling the actual function.

Actually, though, since you already define this function, could you just write the hard name in?

+2
source

Source: https://habr.com/ru/post/897391/


All Articles