get current function name inside that function using python

前端 未结 4 1028
囚心锁ツ
囚心锁ツ 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 07:56

    Actually, Eric's answer points the way if this is about logging:

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

    You can adjust the formatter to log the function name:

    import logging               
    
    def whoami():
        logging.info("Now I'm there")
    
    def foo():
        logging.info("I'm here")
        whoami()
        logging.info("I'm back here again")
    
    logging.basicConfig(
        format="%(asctime)-15s [%(levelname)s] %(funcName)s: %(message)s",
        level=logging.INFO)
    foo()
    

    prints

    2015-10-16 16:29:34,227 [INFO] foo: I'm here
    2015-10-16 16:29:34,227 [INFO] whoami: Now I'm there
    2015-10-16 16:29:34,227 [INFO] foo: I'm back here again
    
    0 讨论(0)
  • 2021-02-01 08:05

    You probably want inspect.getframeinfo(frame).function:

    import inspect
    
    def whoami(): 
        frame = inspect.currentframe()
        return inspect.getframeinfo(frame).function
    
    def foo():
        print(whoami())
    
    foo()
    

    prints

    whoami
    
    0 讨论(0)
  • 2021-02-01 08:14

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

    Have you considered decorators?

    import functools
    def logme(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            print(f.__name__)
            return f(*args, **kwargs)
        return wrapped
    
    
    @logme
    def myfunction():
        print("Doing some stuff")
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
提交回复
热议问题