circuitpython/tests/basics/scope_implicit.py
Damien George 9201f46cc8 py/compile: Fix case of eager implicit conversion of local to nonlocal.
This ensures that implicit variables are only converted to implicit
closed-over variables (nonlocals) at the very end of the function scope.
If variables are closed-over when first used (read from, as was done prior
to this commit) then this can be incorrect because the variable may be
assigned to later on in the function which means they are just a plain
local, not closed over.

Fixes issue #4272.
2018-10-28 00:33:08 +11:00

32 lines
725 B
Python

# test implicit scoping rules
# implicit nonlocal, with variable defined after closure
def f():
def g():
return x # implicit nonlocal
x = 3 # variable defined after function that closes over it
return g
print(f()())
# implicit nonlocal at inner level, with variable defined after closure
def f():
def g():
def h():
return x # implicit nonlocal
return h
x = 4 # variable defined after function that closes over it
return g
print(f()()())
# local variable which should not be implicitly made nonlocal
def f():
x = 0
def g():
x # local because next statement assigns to it
x = 1
g()
try:
f()
except NameError:
print('NameError')