Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python introspection - how to check current module / line of call from within 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 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
like image 954
orokusaki Avatar asked Mar 16 '11 14:03

orokusaki


People also ask

How can we find the names that are defined inside the current module in Python?

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.

How do I see what methods are in a Python module?

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.

What is __ module __ Python?

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.

How do you check if a function is called in Python?

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!'


2 Answers

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))
like image 53
Sven Marnach Avatar answered Nov 14 '22 23:11

Sven Marnach


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
like image 22
samplebias Avatar answered Nov 14 '22 23:11

samplebias