17

Is there a way to find what function called the current function? So for example:

def first():
    second()

def second():
    # print out here what function called this one

Any ideas?

1
  • 4
    @MikeG.: Wanting this information in a production release is bad, yes. Using it to debug and understand a large piece of Python is fine, IMHO. Commented Mar 27, 2010 at 19:18

4 Answers 4

11
import inspect

def first():
    return second()

def second():
    return inspect.getouterframes( inspect.currentframe() )[1]

first()[3] # 'first'
7

These work well for quickly adding minimal where-am-I debugging aids when you don't want to import yet another module. (CPython only, for debugging only.)

def LINE( back = 0 ):
    return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
    return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
    return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
    frame = sys._getframe( back + 1 )
    return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
                            frame.f_lineno, frame.f_code.co_name )

Example:

import sys, os # these you almost always have...

def WHERE( back = 0 ):
    frame = sys._getframe( back + 1 )
    return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
                        frame.f_lineno, frame.f_code.co_name )

def first():
    second()

def second():
    print WHERE()
    print WHERE(1)

first()

Output:

$ python fs.py
fs.py/12 second()
fs.py/9 first()
2
  • Is there any way to check if it is deep enough before the call, when I call WHERE(1) from the top parent function I get get following error: ValueError: call stack is not deep enough
    – alper
    Commented Feb 24, 2020 at 11:01
  • Thanks, I put it in a loop and successfully retrieved a problematic function in one of my scripts ! Here's a gist: gist.github.com/corentinbettiol/…
    – sodimel
    Commented Oct 30, 2020 at 10:43
4

You can use the traceback module's extract_stack function.

import traceback
def first():
    second()

def second():
    print traceback.extract_stack(limit=2)[-2][2]
2

The inspect module allows for many forms of introspection including this one, but note that it's only recommended to use such information for purposes such as debugging, not as part of your production code's functionality. See the docs for all details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.