How to get a function name as a string?

后端 未结 12 2244
后悔当初
后悔当初 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条回答
  •  Happy的楠姐
    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

提交回复
热议问题