Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine where a function was executed?

Tags:

python

how should I define a function, where,which can tell where it was executed, with no arguments passed in? all files in ~/app/

a.py:

def where():
    return 'the file name where the function was executed'

b.py:

from a import where
if __name__ == '__main__':
    print where() # I want where() to return '~/app/b.py' like __file__ in b.py

c.py:

from a import where
if __name__ == '__main__':
    print where() # I want where() to return '~/app/c.py' like __file__ in c.py
like image 240
walknotes Avatar asked Apr 30 '13 17:04

walknotes


People also ask

How do you know when a function is called?

In Chrome, you can use: console. trace(); Just add that line in your function, I usually place it as the first line. If you view the console you'll see the name of your function, and below that line you'll see where it's being called from.


1 Answers

You need to look up the call stack by using inspect.stack():

from inspect import stack

def where():
    caller_frame = stack()[1]
    return caller_frame[0].f_globals.get('__file__', None)

or even:

def where():
    caller_frame = stack()[1]
    return caller_frame[1]
like image 115
Martijn Pieters Avatar answered Oct 08 '22 05:10

Martijn Pieters