How to get a function name as a string?

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

提交回复
热议问题