nonlocal fails ?

MRAB python at mrabarnett.plus.com
Thu Nov 14 08:44:30 EST 2019


On 2019-11-14 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..
> 
In section 7.13 of the Help it says:

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

'nonlocal' is used where the function is nested in another function and 
you want to be able to bind to the variables in the enclosing function.

In your code, there's no enclosing function. Instead, you want to be 
able to bind to the module's global variables. For that, you should use 
'global' instead.

def Proc1():
     global MyVar
     MyVar = 5

MyVar = 7
Proc1()
print(MyVar)


More information about the Python-list mailing list