The nonlocal Statement in Python 3

In Python 3 we can change enclosing scope variables by declaring them in nonlocal statements, so nested defs can have access to names in enclosing functions.

  • The nonlocal declares that a name will be changed in an enclosing scope.
  • The nonlocal applies to a name in an enclosing function’s scope.
  • The nonlocal names must already exist in the enclosing function’s scope when declared. They can exist only in enclosing functions and cannot be created by a first assignment in a nested def.

Examples:

In the example below, the tester1 builds and returns the function motorbike and the quant reference in motorbike maps the local scope of tester1 using the normal scope lookup rules.

>>> def tester1(start):
...     quant = start
...     def motorbike(brand):
...             print(brand, quant)
...     return nested1
... 
>>> bike = tester1(1)
>>> bike('Honda')
Honda 1
>>> bike('Yamaha')
Yamaha 1

If we declare quant in the tester1 scope as nonlocal within motorbike, we get to change it inside the motorbike function, too.

>>> def tester1(start):
...     quant = start
...     def motorbike(label):
...             nonlocal quant
...             print(label, quant)
...             quant += 1
...     return motorbike
... 
>>> bike = tester1(1)
>>> bike('Suzuki')
Suzuki 1
>>> bike('Yamaha')
Yamaha 2
>>> bike('Honda')
Honda 3

Note:

  • Nonlocal names must have previously been assigned in an enclosing def scope when a nonlocal is evaluated.
  • Nonlocal restricts the scope lookup to just enclosing def.

Leave a Reply