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:

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

  • Modifying variables in enclosing scopes, particularly useful in closures
  • Maintaining state in nested functions
  • Avoiding the use of global variables for encapsulation and scope management

Tutorial

Python Inner Functions: What Are They Good For?

In this step-by-step tutorial, you'll learn what inner functions are in Python, how to define them, and what their main use cases are.

intermediate python

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


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader