osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python scope question


I have questions how nonlocal and global affecting the variable assignment. Also how each print statement looking up the values for the spam variable. This scope thing in python is very confusing too me still. Can anyone help me to understand this code w.r.t to scope in Python?

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)


??

$ python3 sample.py 
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam


Thanks,

Arup Rakshit
ar at zeit.io