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.
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 & the LEGB Rule: Resolving Names in Your Code
In this step-by-step tutorial, you'll learn what scopes are, how they work, and how to use them effectively to avoid name collisions in your code. Additionally, you'll learn how to take advantage of a Python scope to write more maintainable and less buggy code.
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)
- Python Inner Functions (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)