Python non local variables

Non local variables are used to access local variables in the scope of the parent function from a nested (child) function. The referenced variable must not be global i.e. should not have global <variable_name> keyword in the parent function and can also not be a local variable in the nested function .i.e. a variable local to the nested function cannot be nonlocal.

This construct helps nested function access variables of the parent function therefore memory is saved as the same memory address is reused.

Also to note is that nonlocal keyword cannot only be used in the context of nested functions.

Let’s explore this by examples.

Example 1

When we run the above program, we get output as below

Explanation:

On line 4 under function innerprintname(),we reference the local variable name from parent function printname().We then assign the value “Doe” to it and this changes the value from the parent function as well. This then explains why the value of name is “Doe” as is evident when we print its values from both the nested and the parent functions.

Example 2- What if we comment line 4?What will be the output?Lets go ahead and see

When we run the program, we get below output

Explanation:Each function assigns value to its own name variable hence no variable re-use.Therefore,different values of name are held as shown in the output.

Example 3-nonlocal on a global variable

When we run the above program,we get below output

Explanation:On line 4,we use nonlocal keyword on global variable name.Variable name is global since its outside the scope of function printname() which is the parent of innerprintname().This is a violation of the use of nonlocal therefore the error.

Example 4-nonlocal on a local variable

On running the above program, we get below output

Explanation:

On line 4,we are applying nonlocal to a local variable-name.This is illegal therefore the error output.

Example 5

When we run the above program,we get output as below

Explanation

In function one(),the value of name(global variable) is “John”,in function two,the value of name(local variable) is “Doe” and in function three,the value of name(local variable) is “Stacks”.

Let’s uncomment line 6 and rerun the program

Example 6

Output of above program

Explanation

In function one(),the value of name(global variable) is “John”,in function two,the value of name is “Stacks” since it a new value (“Stacks”)has been assigned on line 7 whereby name from function two() has been referenced on line 6.Subsequently,the value at function three() is “Stacks” as per execution of line 7.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.