6

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

3 Answers 3

13

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))
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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 the line numbers. Using the warnings module is great because the user of your module can disable warnings, or turn them into fully inspectable exceptions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.