course content

Course Content

Mastering Python: Closures and Decorators

Non-local ScopeNon-local Scope

The non-local scopes are outer local scopes. This means that the non-local scope is placed between global scope and function local scope:

Let's look at the code example:

Code Description
In this code, there are three nested functions: first_outer(), second_outer(), and inner(). Each function creates its own local scope. The non-local scope, also known as the enclosing scope, is a concept that allows inner functions to access variables from their immediate outer function's scope, but not from the global scope.

Let's break down the code and examine the non-local scope interactions:

  1. first_outer() function:
  2. - Creates a local variable first with the value "first_outer() local scope".
    - Calls the second_outer() function.

  3. second_outer() function:
  4. - Creates a local variable second with the value "second_outer() local scope".
    - Calls the inner() function.

  5. inner() function:
  6. - Creates a local variable third with the value "inner() local scope".
    - Attempts to access the variables first and second, which are not directly defined within its local scope.

Since inner() cannot find first and second in its local scope, it looks in its non-local scope, which is the immediate outer function's scope (second_outer() in this case). It successfully finds and accesses both first and second from the non-local scopes of second_outer() and first_outer() respectively.

The first_outer() local and second_outer() local scope are non-local scopes for the inner() function.

Access to change non-local objects

You can change the non-local variable or another object using the nonlocal keyword (similar to the global keyword):

Code Description
In this code, we have two functions: outer() and inner(). The variable some_variable is defined in the outer() function's local scope. The inner() function is nested inside the outer() function.

The nonlocal keyword is used inside the inner() function to indicate that the variable some_variable is not a local variable of inner() or global but belongs to its non-local scope (outer() in this case). This allows inner() to access and modify the non-local variable some_variable.

When we call the inner() function, it prints the value of some_variable, which is 255. Then, it increments the value of some_variable by 233, resulting in some_variable being 488.

Therefore, the nonlocal keyword allows us to modify non-local variables, just like the global keyword allows us to modify global variables from within a function's local scope.


Why pay attention to non-local scope?
The non-local scope is used for the closure. That's why non-local scope is also named enclosing scope. The closure will be described in the next section.

Everything was clear?

Section 1. Chapter 4