Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python nonlocal

def to_string(node):
    def actual_recursive(node):
        nonlocal a_str		# ~global, can modify surrounding function's scope.
        a_str += str(node.val)
        if node.next != None:
            actual_recursive(node.next)
    a_str = ''
    actual_recursive(node)
    return a_str
Comment

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
Comment

PREVIOUS NEXT
Code Example
Python :: convert generator to list python 
Python :: fetch row where column is missing pandas 
Python :: password guessing game python 
Python :: addition of matrix in python using numpy 
Python :: python inject into process 
Python :: python index max list 
Python :: how to access variables from a class in python 
Python :: how to select li element in selenium python 
Python :: linking bootstrap in flask 
Python :: python delete directory contents 
Python :: static files not loading 404 error django 
Python :: python file write 
Python :: matp[lotlib max y value 
Python :: python lists tuples sets dictionaries 
Python :: str replace pandas 
Python :: how to print all items in a list python 
Python :: lasso regression 
Python :: how to import pandas in python 
Python :: how to cut image python 
Python :: python slit 
Python :: append to set python 
Python :: get array dimension numpy 
Python :: change value in excel in python 
Python :: pandas remove repeated index 
Python :: django orm group by month and year 
Python :: django admin create project 
Python :: load python file in jupyter notebook 
Python :: video capture opencv and multiprocessing 
Python :: how to create multidimensional array in python using numpy 
Python :: uninstall python3 from source on centos 7 
ADD CONTENT
Topic
Content
Source link
Name
6+7 =