nonlocal fails ?

Jan Erik Moström lists at mostrom.pp.se
Thu Nov 14 08:21:45 EST 2019


On 14 Nov 2019, at 14:06, R.Wieser wrote:

> I've also tried moving "MyVar = 7" to the first line, but that doesn't
> change anything.  Using "global MyVar" works..

Try

def outer():
	MyVar = 10
	def Proc1():
		nonlocal MyVar
		MyVar = 5
	Proc1()
	
MyVar = 7
outer()
print(MyVar)

 From the documentation

The nonlocal statement causes the listed identifiers to refer to 
previously bound variables in the nearest ******enclosing scope 
excluding globals******. This is important because the default behavior 
for binding is to search the local namespace first. The statement allows 
encapsulated code to rebind variables outside of the local scope besides 
the global (module) scope.

Names listed in a nonlocal statement, unlike those listed in a global 
statement, must refer to pre-existing bindings in an enclosing scope 
(the scope in which a new binding should be created cannot be determined 
unambiguously).

Names listed in a nonlocal statement must not collide with pre-existing 
bindings in the local scope.


More information about the Python-list mailing list