How to get a function name as a string?

后端 未结 12 2228
后悔当初
后悔当初 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: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.

提交回复
热议问题