Arghya Saha
Arghya Saha

Reputation: 5733

Python nested function

I came across this interesting code

# Define echo
def echo(n):
    """Return the inner_echo function."""

    # Define inner_echo
    def inner_echo(word1):
        """Concatenate n copies of word1."""
        echo_word = word1 * n
        return echo_word

    # Return inner_echo
    return inner_echo


# Call echo: twice
twice = echo(2)

# Call echo: thrice
thrice = echo(3)

# Call twice() and thrice() then print
print(twice('hello'), thrice('hello'))

output :

hellohello hellohellohello

But I'm not able to understand how it is working since twice and thrice functions is calling the function echo and providing the value n, how is the value of word1 is passed?

Upvotes: 3

Views: 1296

Answers (4)

Shadow
Shadow

Reputation: 9447

The echo function returns another function, that has n set to whatever you pass it. When you call inner_echo (ie, the return of echo) it keeps the scope that it was given when created.

In your example, twice is created using echo(2) which returns the inner_echo function which, in it's scope, n is set to 2.

Likewise, thrice, created by echo(3) creates a new version of inner_echo, where n is set to 3.

Remember how echo returns a function? When you call twice or thrice you are calling the function that echo returned - ie, you are not calling echo at all. Therefore calling twice is calling inner_echo and that is how word is being populated.

Upvotes: 1

Aluan Haddad
Aluan Haddad

Reputation: 31873

echo is a function that takes a parameter n and returns another function that closes over the supplied value of n and also takes an argument word1.

In other words, calling echo(n) for some n returns a function which is then called with twice(word1)

The flow is essentially.

echo = function (n) -> function (word1) with closure (n) -> word1 repeated n times

twice = echo (2) -> function (word1) with closure (n = 2) -> word1 repeated 2 times

twice('hello') -> 'hello' repeated 2 times

I have described it in the above manner because, AFAICT Python does not have a syntax for expressing the types of functions.

Upvotes: 1

Sanket
Sanket

Reputation: 745

The above example is the example of Function Closures

Better you can refer this link Function Closure In Python

Upvotes: 0

Sumit S Chawla
Sumit S Chawla

Reputation: 3600

When you call echo with a value 2 in twice = echo(2) , it stores the value 2 internally. So when we call twice('hello'), it remembers the value of n and prints it that many times. When you pass 3 to the same function as thrice = echo(3) , it stores the value 3 internally.

So, basically it is creating instances with different values of n. I hope you understood.

Try passing it twice = echo(2) and then twice = echo(3) , In this case it will update the value of n.

Upvotes: 0

Related Questions