Getting the caller function name inside another function in Python?

There are two ways, using sys and inspect modules:

  • sys._getframe(1).f_code.co_name
  • inspect.stack()[1][3]

The stack() form is less readable and is implementation dependent since it calls sys._getframe(), see extract from inspect.py:

def stack(context=1):
    """Return a list of records for the stack above the caller's frame."""
    return getouterframes(sys._getframe(1), context)

You can use the inspect module to get the info you want. Its stack method returns a list of frame records.

  • For Python 2 each frame record is a list. The third element in each record is the caller name. What you want is this:

    >>> import inspect
    >>> def f():
    ...     print inspect.stack()[1][3]
    ...
    >>> def g():
    ...     f()
    ...
    >>> g()
    g
    

  • For Python 3.5+, each frame record is a named tuple so you need to replace

    print inspect.stack()[1][3]
    

    with

    print(inspect.stack()[1].function)
    

    on the above code.