Yogesh Thakre
Yogesh Thakre

Reputation: 13

Returning Nested Functions in Python

def raise_val(n):
    """Return the inner function."""

    def inner(x):
    """Raise x to the power of n."""
        raised = x ** n
        return raised

    return inner

square = raise_val(2)

cube = raise_val(3)

print(square(2), cube(4))

Outputs:

4 64

Can anybody explain to me how come square(2) knows that the argument passed is x?

Upvotes: 1

Views: 1607

Answers (2)

Sarthak chauhan
Sarthak chauhan

Reputation: 36

this code uses the concept of lexical closures or closures.Closures are the function that remembers the parameters passed to their parent function.The more technical definition will be,Closures are the function that remembers values in enclosing scope even if they are not actually present in the memory.

#for example`
def outer(x):
    def inner():
        print(f"The argument passed to outer was {x}")
    '''Notice how inner() will grab the argument passed to the outer function'''

     return inner

value=outer(69)

print(value())

Upvotes: 1

Roim
Roim

Reputation: 3066

Maybe this will help: https://stackabuse.com/python-nested-functions/

Notice you "sends arguments twice" (not really): first in square = raise_val(2) and second in square(2). What happens? The first calls return a function: you call to raise_val and it returns inner, which is a function. Now square variable actually holds a function. Second call, square(2), just call to the function.

It's the same as:

def a(x):
   print(x)

square = a 
print(square(5))

In this example, square holds a function. It's the same as in your code, since raise_val returns a function. Square holds inner method, and later it is been called. You send x directly: square(2) sends 2 for x of course. A more interesting can be "how inner remembers n?", and as others mentioned in comments: it's manages variables of current scope.

Upvotes: 1

Related Questions