Can a closure modify a mutable object in the outer scope without `nonlocal`? Why?

Python interview question for Advanced practice.

Answer

Yes, a closure can mutate an object (like appending to a list or setting a dict key) without nonlocal. Reason: This is because you are not changing what the variable name data points to; you are dereferencing data to find the list object, and then calling a method on that object. nonlocal is only required if you want to assign a new object to the name data (data = []), which changes the binding in the scope.

Explanation

You only need nonlocal to rebind the name itself, not to modify the object it points to.

Related Questions