Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use inspect to get the caller's info from callee in Python?

Tags:

python

inspect

I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how.

How to get those info with inspect? Or is there any other way to get the info?

import inspect  print __file__ c=inspect.currentframe() print c.f_lineno  def hello():     print inspect.stack     ?? what file called me in what line?  hello() 
like image 552
prosseek Avatar asked Sep 14 '10 17:09

prosseek


People also ask

How do you inspect a module in Python?

The inspect module helps in checking the objects present in the code that we have written. As Python is an OOP language and all the code that is written is basically an interaction between these objects, hence the inspect module becomes very useful in inspecting certain modules or certain objects.

What is a frame object Python?

Stack frame object represents a program scope in Python. This object contains information about current execution state like code object, local and global variables and a lot of other data. Frames are stored in a stack-like structure.

What is a stack frame Python?

A stack frame represents a single function call. You can visualize functions that call one another as virtual frames stacking on top of one another. The stack data structure is actually used for this! When one function call returns its data to its caller, then its stack frame is removed from the stack.


Video Answer


2 Answers

The caller's frame is one frame higher than the current frame. You can use inspect.currentframe().f_back to find the caller's frame. Then use inspect.getframeinfo to get the caller's filename and line number.

import inspect  def hello():     previous_frame = inspect.currentframe().f_back     (filename, line_number,       function_name, lines, index) = inspect.getframeinfo(previous_frame)     return (filename, line_number, function_name, lines, index)  print(hello())  # ('/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0) 
like image 182
unutbu Avatar answered Nov 15 '22 13:11

unutbu


I would suggest to use inspect.stack instead:

import inspect  def hello():     frame,filename,line_number,function_name,lines,index = inspect.stack()[1]     print(frame,filename,line_number,function_name,lines,index) hello() 
like image 23
Dmitry K. Avatar answered Nov 15 '22 14:11

Dmitry K.