Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

nonlocal keyword python

# nonlocal
# The nonlocal keyword is used to work with variables inside nested functions, 
# without 'nonlocal', variable can be accessible but not modified
# with 'nonlocal' declared, you can modify the variable inside nested function

# example with nonlocal keyword
def foo():
    def foo2():
        nonlocal x
        x = "modified"
    x = "outer function"
    foo2()
    return x

print(foo())
#modified

# example without nonlocal keyword
def foo():

    def foo2():
        x = "cannot be modified without nonlocal declaration"
    
    x = "outer function"
    foo2()
    return x

print(foo())
#outer function

# combined example + triple nested fxn
# “nonlocal” only works in nested functions
def outer():
    def inner():
        def innerest():
            global x      # if declare "nonlocal" here would give an error
            x = "innerest function"
            print("innerest:", x)
        innerest()
    global x
    x = "outer function"
    print("outer:", x)
    inner()

x = "global"
print('global:', x)
outer()

# global: global
# outer: outer function
# innerest: innerest function
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #nonlocal #keyword #python
ADD COMMENT
Topic
Name
7+4 =