Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python nonlocal statement

What does the Python nonlocal statement do (in Python 3.0 and later)?

There's no documentation on the official Python website and help("nonlocal") does not work, either.

like image 720
ooboo Avatar asked Aug 11 '09 17:08

ooboo


People also ask

What is nonlocal variable Python?

In python, nonlocal variables refer to all those variables that are declared within nested functions. The local scope of a nonlocal variable is not defined. This essentially means that the variable exists neither in the local scope nor in the global scope.

Should you use nonlocal Python?

nonlocal completely encapsulates that information in a namespace dedicated to the particular run of your outer function. There is really no downside here. Using instance attributes makes that information available to anyone using the instance. This is unnecessary conceptually, marginally slower, and not thread-safe.

What is nonlocal and global in Python?

A nonlocal variable has to be defined in the enclosing function scope. If the variable is not defined in the enclosing function scope, the variable cannot be defined in the nested scope. This is another difference to the "global" semantics.

What is the use of locals () in Python?

Python locals() Function The locals() function returns the local symbol table as a dictionary. A symbol table contains necessary information about the current program.


2 Answers

Compare this, without using nonlocal:

x = 0 def outer():     x = 1     def inner():         x = 2         print("inner:", x)      inner()     print("outer:", x)  outer() print("global:", x)  # inner: 2 # outer: 1 # global: 0 

To this, using nonlocal, where inner()'s x is now also outer()'s x:

x = 0 def outer():     x = 1     def inner():         nonlocal x         x = 2         print("inner:", x)      inner()     print("outer:", x)  outer() print("global:", x)  # inner: 2 # outer: 2 # global: 0 

If we were to use global, it would bind x to the properly "global" value:

x = 0 def outer():     x = 1     def inner():         global x         x = 2         print("inner:", x)      inner()     print("outer:", x)  outer() print("global:", x)  # inner: 2 # outer: 1 # global: 2 
like image 108
Anon Avatar answered Nov 09 '22 15:11

Anon


In short, it lets you assign values to a variable in an outer (but non-global) scope. See PEP 3104 for all the gory details.

like image 26
Arkady Avatar answered Nov 09 '22 13:11

Arkady