Python dynamically gets the name of the currently running class and function

  • 2020-04-02 13:33:23
  • OfStack

Use built-in methods and decorator methods to get the class name, function name

Get the function name either internally or externally in python, get it from the external case, use the object that points to the function, and then use the s/s attribute

def a():pass
a.__name__

In addition to:
getattr(a,'__name__')

Despite some of the pants and farts, the method of getting them from the outside is very flexible.

Some of you need to get the name of the function from inside the function, which is a little tricky.
1. Method of using sys module:


def a():
print sys._getframe().f_code.co_name

F_code and co_name refer to the pyc generation and namespace sections of python source code parsing.
2. Methods of using modifiers:
Using the modifier you can point to a variable for the function and then take the s/s method of the variable object.
def timeit(func):
def run(*argv):
   print func.__name__
   if argv:
    ret = func(*argv)
   else:
    ret = func()
   return ret
return run
@timeit
def t(a):
print a 
t(1)

Use the inspect module to dynamically get the name of the currently running function



import inspect
def get_current_function_name():
    return inspect.stack()[1][3]
class MyClass:
    def function_one(self):
        print "%s.%s invoked"%(self.__class__.__name__, get_current_function_name())
if __name__ == "__main__":
    myclass = MyClass()
    myclass.function_one()

Getting the name of the currently running function dynamically is handy, especially for some debug systems


Related articles: