Here is the example:
def foo1():
res = 0
def foo2():
nonlocal res
res = 10
return 20
rv = foo2()
res = rv
print(res)
foo1() # output: 30
res
is increased by 10 in closure, becoming 10, then plus 10 returned by foo2
, resulting in 20 consequently. So far, so good.
Here is an another similar case:
def foo1():
res = 0
def foo2():
nonlocal res
res = 10
return 20
res = foo2()
print(res)
foo1() # output: 20
Strangely, it outputs 10.
It seems that res
is re-defined in res = foo2()
. Do I think right?
Why is the result 10 at above example? what results in this?
- CPython 3.6.9
CodePudding user response:
Based on the symptom, in stack pseudo-code it is acting like
push res, push foo2(), add, pop res
So the change to res
in the middle of foo2
has no effect on the result. Because it "grabbed" the value of res
BEFORE foo2
, and used that in the expression.
Or you could show the pseudo-code like this:
temp1 = res
temp2 = foo2()
temp1 = temp1 temp2
res = temp1
CodePudding user response:
In Both examples: foo2() is a function which returns a value.(i.e. 10) So, In first you catched that value and stored it in rv and at the same time res is incremented by 10 so now value of res=10 and rv=10 therefore In 1st example output is 20
Whereas in 2nd example, foo2() is called after the res is 0 so res=0 10 therefore In 2nd example output is 10