How to get a function name as a string?

后端 未结 12 2075
后悔当初
后悔当初 2020-11-22 04:35

In Python, how do I get a function name as a string, without calling the function?

def my_function():
    pass

print get_function_name_as_string(my_function         


        
相关标签:
12条回答
  • 2020-11-22 04:50

    I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:

    class EnterExitLog():
        def __init__(self, funcName):
            self.funcName = funcName
    
        def __enter__(self):
            gLog.debug('Started: %s' % self.funcName)
            self.init_time = datetime.datetime.now()
            return self
    
        def __exit__(self, type, value, tb):
            gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
    
    def func_timer_decorator(func):
        def func_wrapper(*args, **kwargs):
            with EnterExitLog(func.__name__):
                return func(*args, **kwargs)
    
        return func_wrapper
    

    so now all you have to do with your function is decorate it and voila

    @func_timer_decorator
    def my_func():
    
    0 讨论(0)
  • 2020-11-22 04:53
    my_function.func_name
    

    There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.

    import dis
    dis.dis(my_function)
    

    will display the code in almost human readable format. :)

    0 讨论(0)
  • 2020-11-22 04:53
    import inspect
    
    def foo():
       print(inspect.stack()[0][3])
    

    where

    • stack()[0] is the caller

    • stack()[3] is the string name of the method

    0 讨论(0)
  • 2020-11-22 04:56
    my_function.__name__
    

    Using __name__ is the preferred method as it applies uniformly. Unlike func_name, it works on built-in functions as well:

    >>> import time
    >>> time.time.func_name
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    AttributeError: 'builtin_function_or_method' object has no attribute 'func_name'
    >>> time.time.__name__ 
    'time'
    

    Also the double underscores indicate to the reader this is a special attribute. As a bonus, classes and modules have a __name__ attribute too, so you only have remember one special name.

    0 讨论(0)
  • 2020-11-22 04:56

    If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.

    def my_function():
        pass
    
    class MyClass(object):
        def method(self):
            pass
    
    print(my_function.__name__)         # gives "my_function"
    print(MyClass.method.__name__)      # gives "method"
    
    print(my_function.__qualname__)     # gives "my_function"
    print(MyClass.method.__qualname__)  # gives "MyClass.method"
    
    0 讨论(0)
  • 2020-11-22 04:57

    Try

    import sys
    fn_name = sys._getframe().f_code.co_name
    

    further reference https://www.oreilly.com/library/view/python-cookbook/0596001673/ch14s08.html

    0 讨论(0)
提交回复
热议问题