I've been following the tutorial in the Python docs and I came across the code about the use of the global
and nonlocal
keywords. I've read through the code but I don't quite understand why some of the code does what it does. Here's the code:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
Printout:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
After the do_global()
call, why does spam
print out nonlocal spam
? Shouldn't it be printing out global spam
?
Thanks!