Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of outer function from inner function object in python

Tags:

python

Assume a nested function in python, where outer denotes the outer function and inner denotes the inner function. The outer function provides parametrization of the inner function and returns an instance of this parametrized function.

I want to obtain the name of the outer function, given an instance of the inner function which is returned by the outer function. The code is as follows:

def outer(a):
    def inner(x):
        return x*a
    return inner
p = outer(3)
print p  # prints inner
print p(3)  # prints 9

How can I print the name of the outer function, ie outer, given only p? Thanks!

like image 640
the_max Avatar asked Sep 26 '22 18:09

the_max


1 Answers

You can use functools.wraps:

from functools import wraps

def outer(a):
    @wraps(outer)
    def inner(x):
        return x*a
    return inner
p = outer(3)
print p  # <function outer at ...>
like image 124
Vincent Savard Avatar answered Oct 11 '22 05:10

Vincent Savard