nested scope
In Python, a nested scope refers to the ability of an inner function to access variables from its containing or enclosing function. This concept is part of the broader scope in Python, which includes local, enclosing, global, and built-in scopes.
When you define a function inside another function, the inner function can see and use the variables defined in the outer function. This is possible because Python retains access to the outer scope for the inner function, even after the outer function has finished executing.
By default, a nested scope works only for reading an enclosing variable, not for assigning to it. Assigning to the name inside the inner function makes it local to that function instead, which raises an UnboundLocalError if the inner function also reads it. To rebind a name in the enclosing scope, declare it with the nonlocal keyword.
Nested scopes are useful when you need to encapsulate functionality and create closures.
Example
Here’s an example of nested scopes in Python:
>>> def outer_function(message):
... def inner_function():
... print(message)
... return inner_function
...
>>> function = outer_function("Hello, Real Python!")
>>> function()
Hello, Real Python!
In this example, inner_function() is defined inside outer_function(). It accesses the message variable, which is in the enclosing scope defined by outer_function(). When you call function(), it prints "Hello, Real Python!" because it retains access to the message variable from the outer_function() scope.
Related Resources
Tutorial
Python Scope and the LEGB Rule: Resolving Names in Your Code
Understanding Python's variable scope and the LEGB rule helps you avoid name collisions and unexpected behavior. Learn to manage scope and write better code.
For additional information on related topics, take a look at the following resources:
- Exploring Scopes and Closures in Python (Course)
- Python Inner Functions: What Are They Good For? (Tutorial)
- Python Closures: Common Use Cases and Examples (Tutorial)
- Namespaces in Python (Tutorial)
- The LEGB Rule & Understanding Python Scope (Course)
- Python Scope and the LEGB Rule: Resolving Names in Your Code (Quiz)
- Python Inner Functions (Course)
- Python Inner Functions: What Are They Good For? (Quiz)
- Exploring Python Closures: Examples and Use Cases (Course)
- Python Closures: Common Use Cases and Examples (Quiz)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces in Python (Quiz)
- Namespaces and Scope in Python (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.