Python introspection - how to check the current module / call line from a function

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 this 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 
+6
python introspection
source share
3 answers

Access to the inspect.currentframe() framework:

 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)) 
+13
source share

The traceback module allows you to traceback stack so you can see how you reached the current frame frame. If you want, you can expand it to print the caller as far from the stack as possible:

 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 
+3
source share

Use the warnings module.

 import warnings def test(where): warnings.warn('hi from test', stacklevel=2) def foo(): test('inside foo') test('from main module') foo() 

Results:

 /tmp/test.py:9: UserWarning: hi from test test('from main module') /tmp/test.py:7: UserWarning: hi from test test('inside foo') 

Check line numbers. Using the warnings module warnings great, because the user of your module can turn off warnings or turn them into completely controlled exceptions.

+1
source share

All Articles