How to use inspect to get the caller's info from callee in Python?
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)
Get in a python function the name of the caller function file
use inspect module :
import inspect
def log(message):
frm = inspect.stack()[1].filename
print('[%s] %s' % (frm, message))
How to get the caller's method name in the called method?
inspect.getframeinfo and other related functions in inspect
can help:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print('caller name:', calframe[1][3])
...
>>> f1()
caller name: f1
this introspection is intended to help debugging and development; it's not advisable to rely on it for production-functionality purposes.
How to access a caller method's __class__ attribute from a callee function in Python?
The implicit __class__
reference is created at compile-time only if you actually reference it within the method (or use super
). For example this code:
class Foo:
def bar(self):
print('bar', locals())
def baz(self):
print('baz', locals())
if False:
__class__
if __name__ == '__main__':
foo = Foo()
foo.bar()
foo.baz()
Produces this output:
bar {'self': <__main__.Foo object at 0x10f45f978>}
baz {'self': <__main__.Foo object at 0x10f45f978>, '__class__': <class '__main__.Foo'>}
To find the calling function's class (in most cases) you could chain together a few CPython-specific inspect
incantations:
- Find the calling function: How to get current function into a variable?
- Find that function's class: Get defining class of unbound method object in Python 3
I wouldn't recommend it.
Getting the caller function name inside another function in Python?
You can use the inspect module to get the info you want. Its stack method returns a list of frame records.
For Python 2 each frame record is a list. The third element in each record is the caller name. What you want is this:
>>> import inspect
>>> def f():
... print inspect.stack()[1][3]
...
>>> def g():
... f()
...
>>> g()
g
For Python 3.5+, each frame record is a named tuple so you need to replace
print inspect.stack()[1][3]
with
print(inspect.stack()[1].function)
on the above code.
Get function callers' information in python
Yes, the sys._getframe()
function let's you retrieve frames from the current execution stack, which you can then inspect with the methods and documentation found in the inspect
module; you'll be looking for specific locals in the f_locals
attribute, as well as for the f_code
information:
import sys
def special_func(x):
callingframe = sys._getframe(1)
print 'My caller is the %r function in a %r class' % (
callingframe.f_code.co_name,
callingframe.f_locals['self'].__class__.__name__)
Note that you'll need to take some care to detect what kind of information you find in each frame.
sys._getframe()
returns a frame object, you can chain through the whole stack by following the f_back
reference on each. Or you can use the inspect.stack()
function to produce a lists of frames with additional information.
how to get the caller's filename, method name in python
You can use the inspect
module to achieve this:
frame = inspect.stack()[1]
module = inspect.getmodule(frame[0])
filename = module.__file__
Get __name__ of calling function's module in Python
Check out the inspect module:
inspect.stack()
will return the stack information.
Inside a function, inspect.stack()[1]
will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.
See the docs for details:
http://docs.python.org/library/inspect.html
Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:
http://pymotw.com/2/inspect/index.html#module-inspect
EDIT: Here's some code which does what you want, I think:
import inspect
def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)
Related Topics
Convert Floating Point Number to a Certain Precision, and Then Copy to String
Creating Dynamically Named Variables from User Input
Expected Conditions in Protractor
How to Save and Load Numpy.Array() Data Properly
Django Return Redirect() with Parameters
Certificate Verify Failed: Unable to Get Local Issuer Certificate
Named Regular Expression Group "(P<Group_Name>Regexp)": What Does "P" Stand For
Importing Pyspark in Python Shell
Downloading File to Specified Location with Selenium and Python
Get Relative Path from Comparing Two Absolute Paths
Valueerror: Numpy.Dtype Has the Wrong Size, Try Recompiling
How to Use SQL Parameters with Python
Fastest Way to Take a Screenshot with Python on Windows
Login Credentials Not Working with Gmail Smtp
Sqlalchemy: What's the Difference Between Flush() and Commit()
Which Tkinter Modules Were Renamed in Python 3