How to get a function name as a string?

后端 未结 12 2082
后悔当初
后悔当初 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'}
    

提交回复
热议问题