nonlocal keyword

5 years ago 45

The nonlocal keyword is used to allow an inner function to access variables defined in an outer function. Without using the nonlocal keyword a new variable will be created in the inner function and will have no effect on the outer function's variables. The below example demonstrates this by defining two versions of s. The first s is accessible only to the outer function say_hello and the other s is only accessible to the inner function say_it. def say_hello(): s = "Hello from outer function say_hello" def say_it(): s = "Hello from inner function say_it" print(s) print(s) say_it() say_hello() The below code demonstrates how to access the outer function's local variable s. By using the nonlocal keyword, say_hello and say_it are sharing the variable s. def say_hello(): s = "Hello from outer function say_hello" def say_it(): nonlocal s s = "Hello from inner function say_it" print(s) #print s before it is modified by say_it say_it() #change the value of s print(s) #print the new value after its modified by say_it say_hello() The concept is very similar to the usage of the global keyword. The difference is global is used to allow a function access to variables defined as global ( actually module attributes ) while nonlocal allows access to variables defined in outer functions.


View Entire Post

Read Entire Article