Determine where a function was executed?

python

Solution

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]

Problem

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 ```

Original source