The following python example is from here:
def f1():
x = 99
def f2():
def f3():
print(x)
print('f3')
f3()
f2()
f1()
and this is the output:
99
f3
Why isn't the output the following?
99
f3 # from f1()
99
f3 # from f3()
99
f3 # from f2()
-
1@lmiguelvargasf I believe the question is really about the call stack, not scope.juanpa.arrivillaga– juanpa.arrivillaga2018年08月07日 05:55:39 +00:00Commented Aug 7, 2018 at 5:55
3 Answers 3
It is because as the code is unwrapped it simplifies to:
x = 99
print(x)
print('f3')
This is the sequence of unwrapping:
def f1():
x = 99
def f2():
def f3():
print(x)
print('f3')
f3()
f2()
f1()
becomes
x = 99
def f2():
def f3():
print(x)
print('f3')
f3()
f2()
becomes
x = 99
def f3():
print(x)
print('f3')
f3()
becomes
x = 99
print(x)
print('f3')
which is then what is executed.
Comments
Consider the code:
def f():
print(123)
which when executed won't print anything. def is only defining the function - it's not executed until we do f().
Similarly your example only defines the inner functions, but only when f3 is called do the print statements execute.
Comments
You should consider the Python scope rules (LEGB). PYthon will look for:
L: local variables
E: enclosing variables (variables defined in enclosing functions)
G: global variables (variables at the zero-indent level)
B: built-in variables
How your program is executed:
f1is defined and thenf1is called- When
f1is called,xtakes the value of99, thenf2is defined, and thenf2is called. - When
f2is called,f3is defined, and thenf3is called. - When
f3is called,xis printed, and since there is no localxinf3, it uses theenclosingx that is local tof1. Then, you are printing exactly the string"f3"with theprintfunction. - Finally,
f3returns,f2returns,f1returns, and your program finishes.