get current function name inside that function using python

前端 未结 4 1037
囚心锁ツ
囚心锁ツ 2021-02-01 07:12

For my logging purpose i want to log all the names of functions where my code is going

Does not matter who is calling the function , i want the the function name in whic

4条回答
  •  攒了一身酷
    2021-02-01 08:18

    Call sys._getframe() to get a frame class instance. The f_code.co_name member holds the function name.

    sys._getframe(0).f_code.co_name
    

    Add a simple helper function func_name() to wrap the call

    import sys
    
    def func_name(): 
        return sys._getframe(1).f_code.co_name
    
    def func1():
        print(func_name())
    
    func1()  # prints 'func1'
    

提交回复
热议问题