Search code examples
pythonfunctionintrospection

How do I know where is a function was executed in Python?


Let's imagine, I've got a module foo.py with declared a function foofunc:

def foofunc():
    # smart things
    return

And two different modules — bar.py and spam.py, where exists code which directly executes the function from foo module.

# `bar` module. All rights reserved.

from foo import foofunc


def run_foofunc():
     return foofunc()

The same thing in another module:

# `spam` module. All rights reserved.

from foo import foofunc


def run_foofunc():
    return foofunc()

I need to know where is executed the function without knowledge of possible places. Something like:

def foofunc():
    print inspect.executedfrom()

Will do something like that in standard output

<pack.bar.run_foofunc>

Does it something similar in real world?


Solution

  • Running the risk of not answering the actual question, you wrote that you need it for research and debugging.

    I think the traceback module is just great for that.

    import traceback
    traceback.print_stack()
    

    Also take a look at pdb, it allows you to interactively step through your code during runtime.