Reputation: 195
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!
Upvotes: 5
Views: 465
Reputation: 5355
This is by no means an elegant solution, and I personally wouldn't use it. However it answers the question that you asked.
def outer(a):
def inner(x):
return x*a
inner.__name__ = 'outer'
return inner
print p
<function outer at 0x10eef8e60>
Upvotes: 0
Reputation: 35927
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 ...>
Upvotes: 4