Search⌘ K
AI Features

nonlocal Scope

Explore how Python's nonlocal keyword works within nested functions to manage variable scope beyond local and global levels. Understand closures and how nonlocal allows assignment to outer scopes, avoiding common errors like UnboundLocalError and SyntaxError. This lesson deepens your grasp of Python's scope rules for more effective coding.

Python 3 added a new keyword called nonlocal. The nonlocal keyword adds a scope override to the inner scope. We 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:

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

If we try ...