Before the nonlocal keyword was added in Python 3 (to this day, if you were stuck on 2.* for any reason), the nested function simply could not repeat the binding of the local barename of its external function - because, as a rule , the assignment operator in barename, for example x = 23 , means that x is the local name for the function containing this operator. global exists (and has existed for a long time) to allow assignments to bind or rearrange file names at the module level, but nothing (except nonlocal in Python 3, as I said) to assign bindings or rename names in an external function.
The solution, of course, is very simple: since you cannot bind or reconfirm such a name, use the non- guest name instead - the index or attribute of some object named in an external function. Of course, the specified object must have a type that allows you to double-check indexing (for example, a list) or one that allows you to bind or restore an attribute (for example, a function), and the list is usually the simplest and most direct approach to this. x is exactly that list in this code example - it exists only to enable the nested function change rebind x[0] .
source share