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:
>>> 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
Related Resources
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.
For additional information on related topics, take a look at the following resources:
- Python Closures: Common Use Cases and Examples (Tutorial)
- Using and Creating Global Variables in Your Python Functions (Tutorial)
- Namespaces and Scope in Python (Tutorial)
- Python Scope & the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Variables in Python: Usage and Best Practices (Tutorial)
- Python Inner Functions (Course)
- Python Closures: Common Use Cases and Examples (Quiz)
- Working With Global Variables in Python Functions (Course)
- Using and Creating Global Variables in Your Python Functions (Quiz)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)