We just witnessed that we can access names from the enclosing scope with nested functions, but we cannot modify them. Python does however provide a way for us to modify names in the enclosing scope, by using the
Given the following enclosing and nested function, there is a variable defined in the enclosing scope, which is not modifiable from within the nested function.
def enclosing_function(): var = "value" def nested_function(): var = "new_value" nested_function() print(var) enclosing_function()
The output would be:
as the value of
var was not modified by the nested function. After using the
nonlocal statement, the variable is now modifiable from the local scope.
def enclosing_function(): var = "value" def nested_function(): nonlocal var var = "new_value" nested_function() print(var) enclosing_function()
The output would now be:
Let’s practice modifying variables in a nested context in our painting application for Jiho!
The users of our applications have requested that we add a way of calculating the amount of paint needed for multiple rooms. To accomplish this the function
calc_paint_amount() now accepts a single parameter
wall_measurements which should be a list of tuples containing the width and height of each wall.
The nested function
calc_square_feet() has been added to iterate through the list and add up the square footage. This function is then called within
Run the code and notice the
UnboundLocalError regarding the variable
square_feet. Move to the next task to fix this.
Since we need to modify
square_feet in an enclosing scope, make sure to mark the variable as
nonlocal in the appropriate place.