1

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()
lmiguelvargasf
71.3k55 gold badges231 silver badges241 bronze badges
asked Aug 7, 2018 at 5:51
1
  • 1
    @lmiguelvargasf I believe the question is really about the call stack, not scope. Commented Aug 7, 2018 at 5:55

3 Answers 3

2

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.

answered Aug 7, 2018 at 6:00
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Aug 7, 2018 at 5:59

Comments

2

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:

  1. f1 is defined and then f1 is called
  2. When f1 is called, x takes the value of 99, then f2 is defined, and then f2 is called.
  3. When f2is called, f3 is defined, and then f3 is called.
  4. When f3 is called, x is printed, and since there is no local x in f3, it uses the enclosing x that is local to f1. Then, you are printing exactly the string "f3" with the print function.
  5. Finally, f3 returns, f2 returns, f1 returns, and your program finishes.
answered Aug 7, 2018 at 5:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.