5

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!

2
  • You cannot. print p only prints 'inner' because 'outer' returns a function that happens to be 'inner' Commented Jan 5, 2016 at 15:57
  • 1
    Actually this is not a bad question, if you are looking for why you cannot do it :) Commented Jan 5, 2016 at 16:07

2 Answers 2

4

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 ...>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, looks like an elegant solution!
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.