Nested Functions and Enclosing Scope
Learn about the enclosing scope, which allows nested functions to access variables defined in their outer (enclosing) function.
We've already learnt that functions can access variables defined in their own local scope, as well as in the global scope.
When we are dealing with nested functions, there's an additional type of scope: the so-called enclosing scope.
The enclosing scope refers to the region where the outer function's variables are accessible by the inner (nested) function.
Even though the inner function has its own scope, it can still access variables from the outer function.
From the perspective of the inner function, there are 3 different scopes:
That means the inner function can access variables defined in the global scope...
And variables defined in the enclosing scope...
And variables defined in its own local scope...
In Python, the way variables are looked up follows a specific order, or hierarchy.
This hierarchy determines where Python starts looking for variable names.
The order goes from inside to outside:
This order is important when multiple variables with the same name exist in different scopes.
For example, in this case, the local version of x
takes precedence over the others:
If there's no local version of x
, the enclosing version takes precedence over the global one:
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?