Python's nonlocal depends on level of hierarchy? Python's nonlocal depends on level of hierarchy? python-3.x python-3.x

Python's nonlocal depends on level of hierarchy?


global and nonlocal are not meant to be combined. They mean different things:

  • global means the name exists at the module level
  • nonlocal means the name exists in an outer lexical function scope

The reason you are getting the original exception is because you told Python that var is nonlocal (meaning it is in an outer function definition), but there is no function-level binding for var in any outer function definition because you told Python in the outer function that var was global.


How can such an example be written in a way that it does not matter at which level a function resides (having to exchange global with nonlocal and vice versa)?

It does not matter at which level a function resides. It only matters at which level the variable resides.

If the functions reside at an intermediate, and unknown level of hierarchy, how could the author of outer() change the code that neither the outermost (in this case global) level, nor the inner() level have to be touched?

You are asking whether it is possible for a function at an intermediate level to, by changing something in its code, to cause a variable in an inner function to alternately change something at a global scope or something in the outer function's local scope. This seems like a really weird thing to be able to do.