Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody please explain the below output?

def closure_add():
    x = 3
    def adder():
        nonlocal x
        x+=1
        return x
    return adder
a = closure_add()
b = closure_add()
print(a())
print(b())
print(b())
print(b())

The output is:

4
4
5
6

If variable 'b' which holds the function 'adder' remembers the scope of variable (x=3), shouldn't the output be '4' no matter how many times you call it.

like image 372
pragun Avatar asked Jan 31 '26 04:01

pragun


1 Answers

Links below should provide more info:

  • Python closures
  • Python nonlocal statement

What this boils down to in the end in your example:

  1. You instantiate two separate function objects in variables a and b
  2. You invoke a once, it increases the value once
  3. You invoke b three times which increases the value three times

Since the value that gets increased in the closure is defined in the method that increases it as nonlocal, the value is stored after each change that is done to it in the parent function, in the x variable.

like image 159
neznidalibor Avatar answered Feb 02 '26 18:02

neznidalibor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!