SoFunction
Updated on 2024-11-15

Python get the name of the current function method examples to share

This article is an example of Python to get the name of the current running function, as follows.

python has a powerful introspection capabilities, in the function runtime, you can get the function name of the current function within the function, see the sample code

#coding=utf-8 
import sys 
import inspect 
 
def my_name(): 
 print '1' ,sys._getframe().f_code.co_name 
 print '2' ,()[0][3] 
 
def get_current_function_name(): 
 print '5', sys._getframe().f_code.co_name 
 return ()[1][3] 
class MyClass: 
 def function_one(self): 
  print '3',()[0][3] 
  print '4', sys._getframe().f_code.co_name 
  print "6 %s.%s invoked"%(self.__class__.__name__, get_current_function_name()) 
 
if __name__ == '__main__': 
 my_name() 
 myclass = MyClass() 
 myclass.function_one() 

The example demonstrates two ways to get the name of the function you are currently in, one using the sys built-in module and one using the inspect module. The results are as follows:

1 my_name 
2 my_name 
3 function_one 
4 function_one 
5 get_current_function_name 
6 MyClass.function_one invoked 

The ().f_code.co_name method always gets the name of the function it is currently in. The () method is relatively more flexible, in the get_current_function_name function, sys gets the name of the function get_cu
rrent_function_name, and the result returned by the inspect method is function_one. records the current in-stack information, and for further information you can print the () information.

I called get_current_function_name in the function_one function, so the first tuple in the list returned by () is the one with information about get_current_function_name, the

It is the second tuple that is the information about function_one.

summarize

Above is this article on Python to get the current function name method to share all the contents of the example, I hope to help you. Interested friends can continue to refer to other related topics on this site, if there are inadequacies, welcome to leave a message to point out. Thank you for the support of friends on this site!