Python gets the current function name method instance share

  • 2020-07-21 08:50:55
  • OfStack

This article focuses on getting the name of the current running function in Python, as follows.

python has powerful introspection that allows you to get the name of the current function inside the function as it runs, as shown in the sample code


#coding=utf-8 
import sys 
import inspect 
 
def my_name(): 
 print '1' ,sys._getframe().f_code.co_name 
 print '2' ,inspect.stack()[0][3] 
 
def get_current_function_name(): 
 print '5', sys._getframe().f_code.co_name 
 return inspect.stack()[1][3] 
class MyClass: 
 def function_one(self): 
  print '3',inspect.stack()[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, using the sys built-in module and the inspect module. The operation 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 sys.getframe ().f_code.co_name method always gets the name of the current function, but the inspect.stack () method is more flexible. In the get_current_function_name method, sys gets the name of the function as get_cu
rrent_function_name, while the inspect method returns function_one. inspect. stack records the current stack information and wants to step one step further to know that inspect. stack() information can be printed.

I called get_current_function_name in the function_one function, so the first tuple in list returned by inspect.stack () is about get_current_function_name information,

The second tuple is the information about function_one.

conclusion

That's all this article has to say about Python getting the current function name method instance to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: