nonlocal fails ?

Rhodri James rhodri at kynesim.co.uk
Thu Nov 14 08:24:26 EST 2019


On 14/11/2019 13:06, R.Wieser wrote:
> Hello all,
> 
> I've just tried to use a "nonlocal MyVar" statement in a procedure
> defenition, but it throws an error saying "Syntax error: no binding for
> nonlocal 'MyVar' found.
> 
> According to platform.python_version() I'm running version 3.8.3
> 
> Why am I getting that error ? (already googeled ofcourse)
> 
> Testcode:
> - - - - - - - - - - - -
> Def Proc1()
>      nonlocal MyVar
>      MyVar = 5
> 
> MyVar = 7
> Proc1()
> print(MyVar)
> - - - - - - - - - - - -
> I've also tried moving "MyVar = 7" to the first line, but that doesn't
> change anything.  Using "global MyVar" works..

The Language Reference says 
(https://docs.python.org/3/reference/simple_stmts.html#the-nonlocal-statement):

"The nonlocal statement causes the listed identifiers to refer to 
previously bound variables in the nearest enclosing scope *excluding 
globals.*"  (my emphasis.)

MyVar is a global here, so nonlocal explicitly doesn't pick it up.

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-list mailing list