« Back to Index

[Python Get Function Name Dynamically At Runtime]

View original Gist on GitHub

Tags: #python #inspect #stack

Python Get Function Name Dynamically At Runtime.py

import inspect
import logging

def logit():
  # go back once in the stack to find the caller of this function
  # e.g. either foo or bar
  logging.warning(inspect.stack()[1].function)

def foo():
    print(inspect.stack()[0])
    print(inspect.stack()[0].function)  # foo
    logit()
    
    def bar():
        print("\n\n", inspect.stack()[0])
        print(inspect.stack()[0].function)  # bar
        logit()
        
    bar()

foo() # kick start the call chain