Global, Local and Nonlocal

Use of nonlocal vs use of global keyword in Python

Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions.

 deffun():
    var1 =10
 
    defgun():
        print(var1)
        var2 =var1 +1
        print(var2)
 
    gun()
fun()
 10
11

 

The variable var1 has scope across entire fun(). It will be accessible from nested function of fun()

 deffun():
    var1 =10
 
    defgun():
        # gun() initializes a new variable var1.
        var1 =20
        print(var1, id(var1))
 
    print(var1, id(var1))
    gun()
fun()
 10 10853920
20 10854240

 

In this case gun() initialized new variable var1 in the scope of gun. var1 with value 10 and var1 with value 20 are two different and unique variables. var1 holding value 20 will be by default accessed in gun().

Considering the previous example, we know that guns will initialize a new variable var1 in its own scope. But when it is going to do so, it cannot find the value of var1 yet, to perform the arithmetic operation as no value has been assigned to var1 previously in gun(). 

 deffun():
    var1 =10
 
    defgun():
        # tell python explicitly that it
        # has to access var1 initialized
        # in fun on line 2
        # using the keyword nonlocal
        nonlocal var1
        var1 =var1 +10
        print(var1)
 
    gun()
fun()

❮ Python Keywords

Example

Make a function inside a function, which uses the variable x as a non local variable:

 
def myfunc1():
  x = "John"
  def myfunc2():
    
    nonlocal x
    x = "hello"
  myfunc2() 
  
    return x

print(myfunc1())

Definition and Usage

The nonlocal keyword is used to work with variables inside nested functions, where the variable should not belong to the inner function.

Use the keyword nonlocal to declare that the variable is not local.

More Examples

Example

Same example as above, but without the nonlocal keyword:

 
def myfunc1():
  x = "John"
  def myfunc2():
    
    x = "hello"
  myfunc2() 
  return x

print(myfunc1())

Related Pages

The keyword global is used to make global variables.

❮ Python Keywords

For more, checkout Geeks For Geeks and W3Schools.