Skip to content

nonlocal

In Python, the nonlocal keyword lets you declare a variable in a nested function as not local to that function. It allows you to modify variables defined in the enclosing scope from within an inner function.

Python nonlocal Keyword Examples

Here’s a quick example to illustrate how the nonlocal keyword works:

Language: Python
>>> def outer_function():
...     number = 10
...     def inner_function():
...         nonlocal number
...         number = 42
...         print("Inner:", number)
...     inner_function()
...     print("Outer:", number)
...

>>> outer_function()
Inner: 42
Outer: 42

In this example, outer_function() defines a variable number and a nested inner_function(). By using the nonlocal keyword inside inner_function(), you tell Python that number refers to the variable in the enclosing scope provided by outer_function(). When inner_function() is called, it changes number to 42, which is then reflected when outer_function() prints number.

Python nonlocal Keyword Use Cases

Python Inner Functions

Tutorial

Python Inner Functions: What Are They Good For?

Learn what a Python inner function is good for: accessing nonlocal names, building stateful closures, and writing your own decorators.

intermediate python

For additional information on related topics, take a look at the following resources:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated July 16, 2026 • Reviewed by Dan Bader