How to get a function name as a string?

后端 未结 12 2060
后悔当初
后悔当初 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 05:01

    I've seen a few answers that utilized decorators, though I felt a few were a bit verbose. Here's something I use for logging function names as well as their respective input and output values. I've adapted it here to just print the info rather than creating a log file and adapted it to apply to the OP specific example.

    def debug(func=None):
        def wrapper(*args, **kwargs):
            try:
                function_name = func.__func__.__qualname__
            except:
                function_name = func.__qualname__
            return func(*args, **kwargs, function_name=function_name)
        return wrapper
    
    @debug
    def my_function(**kwargs):
        print(kwargs)
    
    my_function()
    

    Output:

    {'function_name': 'my_function'}
    
    0 讨论(0)
  • 2020-11-22 05:07

    As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:

    import inspect
    import logging
    import traceback
    
    def get_function_name():
        return traceback.extract_stack(None, 2)[0][2]
    
    def get_function_parameters_and_values():
        frame = inspect.currentframe().f_back
        args, _, _, values = inspect.getargvalues(frame)
        return ([(i, values[i]) for i in args])
    
    def my_func(a, b, c=None):
        logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
        pass
    
    logger = logging.getLogger()
    handler = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s [%(levelname)s] -> %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    
    my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])
    
    0 讨论(0)
  • 2020-11-22 05:07

    sys._getframe() is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback module to do the same thing, eg.

    import traceback
    def who_am_i():
       stack = traceback.extract_stack()
       filename, codeline, funcName, text = stack[-2]
    
       return funcName
    

    A call to stack[-1] will return the current process details.

    0 讨论(0)
  • 2020-11-22 05:11

    You just want to get the name of the function here is a simple code for that. let say you have these functions defined

    def function1():
        print "function1"
    
    def function2():
        print "function2"
    
    def function3():
        print "function3"
    print function1.__name__
    

    the output will be function1

    Now let say you have these functions in a list

    a = [function1 , function2 , funciton3]
    

    to get the name of the functions

    for i in a:
        print i.__name__
    

    the output will be

    function1
    function2
    function3

    0 讨论(0)
  • 2020-11-22 05:13

    To get the current function's or method's name from inside it, consider:

    import inspect
    
    this_function_name = inspect.currentframe().f_code.co_name
    

    sys._getframe also works instead of inspect.currentframe although the latter avoids accessing a private function.

    To get the calling function's name instead, consider f_back as in inspect.currentframe().f_back.f_code.co_name.


    If also using mypy, it can complain that:

    error: Item "None" of "Optional[FrameType]" has no attribute "f_code"

    To suppress the above error, consider:

    import inspect
    import types
    from typing import cast
    
    this_function_name = cast(types.FrameType, inspect.currentframe()).f_code.co_name
    
    0 讨论(0)
  • 2020-11-22 05:13

    This function will return the caller's function name.

    def func_name():
        import traceback
        return traceback.extract_stack(None, 2)[0][2]
    

    It is like Albert Vonpupp's answer with a friendly wrapper.

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