pythoninspect

Get current function name from inside that function using Python


I want to log all the names of functions where my code is going. It does not matter who is calling the function.

import inspect

def whoami():
    return inspect.stack()[1][3]

def foo():
    print(whoami())

Currently it prints foo. I want it to print whoami.


Solution

  • 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