Nonlocal Variables

suggest change

Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope. You can read all about it in PEP 3104. This is best illustrated with a couple of code examples. One of the most common examples is to create function that can increment:

def counter():
    num = 0
    def incrementer():
        num += 1
        return num
    return incrementer

If you try running this code, you will receive an UnboundLocalError because the num variable is referenced before it is assigned in the innermost function. Let’s add nonlocal to the mix:

def counter():
    num = 0
    def incrementer():
        nonlocal num
        num += 1
        return num
    return incrementer

c = counter()
c() # = 1
c() # = 2
c() # = 3

Basically nonlocal will allow you to assign to variables in an outer scope, but not a global scope. So you can’t use nonlocal in our counter function because then it would try to assign to a global scope. Give it a try and you will quickly get a SyntaxError. Instead you must use nonlocal in a nested function.

(Note that the functionality presented here is better implemented using generators.)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Variable Scope and Binding:
* Nonlocal Variables

Table Of Contents
2 Filter
3 List
7 Loops
13 Variable Scope and Binding
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve