nested scope | Python Glossary – Real Python
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.
Nested scopes are useful when you need to encapsulate functionality and create closures.
Example
Here’s an example of nested scopes in 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.
For additional information on related topics, take a look at the following resources:
- 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 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 and Scope in Python (Quiz)
- Namespaces in Python (Quiz)