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.
nonlocaldeclares that a name will be changed in an enclosing scope.
nonlocalapplies to a name in an enclosing function’s scope.
nonlocalnames 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
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
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
- Nonlocal names must have previously been assigned in an enclosing
defscope when a
- Nonlocal restricts the scope lookup to just enclosing