Getting the Caller Function Name Inside Another Function in Python

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.

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.

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)

Determine function name from within that function (without using traceback)

Python doesn't have a feature to access the function or its name within the function itself. It has been proposed but rejected. If you don't want to play with the stack yourself, you should either use "bar" or bar.__name__ depending on context.

The given rejection notice is:

This PEP is rejected. It is not clear how it should be implemented or what the precise semantics should be in edge cases, and there aren't enough important use cases given. response has been lukewarm at best.

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 class name inside a function of another class in python?

Well, after some digging at the prompt, here's what I get:

stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name

print("I was called by {}.{}()".format(the_class, the_method))
# => I was called by A.a()

When invoked:

➤ python test.py
A.a()
B.b()
I was called by A.a()

given the file test.py:

import inspect

class A:
def a(self):
print("A.a()")
B().b()

class B:
def b(self):
print("B.b()")
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name
print(" I was called by {}.{}()".format(the_class, the_method))

A().a()

Not sure how it will behave when called from something other than an object.

Python how to get the calling function (not just its name)?

Calling can happen from any code object (and from an extension module/builtin): from exec, execfile, from module name space (during import), from within a class definition, from within a method / classmethod / staticmethod, from a decorated function/method, from within a nested function, ... - so there is no "calling function" in general, and the difficulty to do anything good with that.

The stack frames and their code objects are the most general you can get - and examine the attributes.


This one finds the calling function in many cases:

import sys, inspect

def get_calling_function():
"""finds the calling function in many decent cases."""
fr = sys._getframe(1) # inspect.stack()[1][0]
co = fr.f_code
for get in (
lambda:fr.f_globals[co.co_name],
lambda:getattr(fr.f_locals['self'], co.co_name),
lambda:getattr(fr.f_locals['cls'], co.co_name),
lambda:fr.f_back.f_locals[co.co_name], # nested
lambda:fr.f_back.f_locals['func'], # decorators
lambda:fr.f_back.f_locals['meth'],
lambda:fr.f_back.f_locals['f'],
):
try:
func = get()
except (KeyError, AttributeError):
pass
else:
if func.__code__ == co:
return func
raise AttributeError("func not found")

# Usage

def f():
def nested_func():
print get_calling_function()
print get_calling_function()
nested_func()

class Y:
def meth(self, a, b=10, c=11):
print get_calling_function()
class Z:
def methz(self):
print get_calling_function()
z = Z()
z.methz()
return z
@classmethod
def clsmeth(cls):
print get_calling_function()
@staticmethod
def staticmeth():
print get_calling_function()

f()
y = Y()
z = y.meth(7)
z.methz()
y.clsmeth()
##y.staticmeth() # would fail

It finds:

<function f at 0x012E5670>
<function nested_func at 0x012E51F0>
<bound method Y.meth of <__main__.Y instance at 0x01E41580>>
<bound method Z.methz of <__main__.Z instance at 0x01E63EE0>>
<bound method Z.methz of <__main__.Z instance at 0x01E63EE0>>
<bound method classobj.clsmeth of <class __main__.Y at 0x01F3CF10>>

However, it may fail to find the function, or find the wrong function, for example, finding the wrong decorator-generated wrapper when the same decorator is used on multiple functions with the same name in different scopes.

call a nested function (function inside another function)

THIS IS NOT SOMETHING YOU SHOULD DO, but you could create a nested function attribute like so:

def foo():
# for closures or strictly local function
# then this is useful!
# ugly hack other wise to try and create methods.
def bar():
print('bar')

# if there are multiple function, return a container...
return bar

Then:

foo.bar=foo()
foo.bar()
# prints 'bar'

BUT, this is far easier with a class:

class Foo:
# class can hold related methods, setters and getters,
# protected variables, etc.
# Python is DESIGNED to do this.
def bar(self):
print('bar')

Then:

f=Foo()
f.bar()
# prints 'bar'

Why is it easier?

  1. Because Python is designed to use the second example, a class, but the first example is a hack. The ways to use classes are well documented and tested.
  2. It does not scale well. Each function attribute needs to be added from the OUTSIDE of the function.
  3. You will run into local vs global namespace issues if you try and change variables. Classes gracefully support both instance and class data.

It is horrible -- don't do it. Use a class or a module to hold methods.


After a morning coffee, you can potentially do something like this if you really want to add function attributes -- Use a decorator to monkey patch a function:

def add_func_to(function):
# decorator to add function attributes
def attr_f(new_func):
setattr(function, new_func.__name__, new_func)
return new_func
return attr_f

# some function to add an attribute function to:
def foo():
pass

@add_func_to(foo)
# added attribute function below
def attr_f(string):
print(string)

Test it:

>>> foo.attr_f('test')
test

This is still limited vs a class or module since you will be limited to using global or passed variables. It is more applicable if you just want to add a function attribute to an existing function and be done with it...

Calling a function of a module by using its name (a string)

Given a module foo with method bar:

import foo
bar = getattr(foo, 'bar')
result = bar()

getattr can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.



Related Topics



Leave a reply



Submit