I have a function:
# utils.py
def hello(name='World'):
# Detect where I'm being called from.
print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno))
# ``mod`` and ``lineno`` on previous line would have been set in real use.
I import that function and run it elsewhere
# other.py (this comment at line # 138)
from utils import hello
hello('Johnny') # From inside ``hello`` I want to be able to detect that this
# was called from other.py at line # 140
The dir() built-in function We can use the dir() function to find out names that are defined inside a module. For example, we have defined a function add() in the module example that we had in the beginning.
Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.
The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.
has_been_called = True return func(*args) wrapper. has_been_called = False return wrapper @calltracker def doubler(number): return number * 2 if __name__ == '__main__': if not doubler. has_been_called: print "You haven't called this function yet" doubler(2) if doubler. has_been_called: print 'doubler has been called!'
Access the enclosing frame of inspect.currentframe()
:
import inspect
def hello(name='World'):
f = inspect.currentframe().f_back
mod = f.f_code.co_filename
lineno = f.f_lineno
print('Hi, %s. You called this from %s at line # %d.' %
(name, mod, lineno))
The traceback
module lets you extract the stack, so you can see how you reached the current stack frame. If you want you can extend this to print the caller-of-caller, as far up the stack as you like:
import traceback
def _trace():
stack = traceback.extract_stack()[-3:-1]
path, line, in_func, _instr = stack[0]
print 'called from %s in func %s at line %s' % (path, in_func, line)
def bar():
_trace()
def foo():
bar()
baz()
def baz():
bar()
bar()
foo()
Output:
called from hello.py in func <module> at line 20
called from hello.py in func foo at line 14
called from hello.py in func baz at line 18
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With