[PYTHON] Note: confusing nonlocal

Probably not used nonlocal

Python 3.9.1 documentation 9.2.1. Scope and namespace examples

Was difficult to read, so I added a comment that I interpreted.

def scope_test():
    def do_local():
        spam = "local spam"
            # do_Assign to local spam
            #Meaningless processing because it is not referenced from anywhere
            #Required for operation explanation

    def do_nonlocal():
        nonlocal spam
            # do_Declared that nonlocal has no spam
            #Functions on the outside(scope_test)Use spam
            #Do not use global spam
        spam = "nonlocal spam"

    def do_global():
        global spam
            #Declared to use global spam
        spam = "global spam"

    #below"spam"Is scope_test stuff
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)

#below"spam"Is global
scope_test()
print("In global scope:", spam)

Is it like this? The reference range of global and nonlocal is exclusive.

Recommended Posts

Note: confusing nonlocal
Note
Note
Note
Django note 4
pyenv note
GroupBy Note
Non-local means
argparse note
Django Note 5
Note: Python
Ansible Note
Python note
Django Note 1
direnv note
Django note 3
Django note 2
[Note] RepresenterError
Note that Python list comprehensions are always confusing