course content

Course Content

Mastering Python: Closures and Decorators

Local ScopeLocal Scope

The functions receive and return data, and the intermediate objects of the function (variables, subfunctions) would only occupy memory, remaining in the global scope. Also, the functions could corrupt other data in the global scope if they were without an isolated scope. That is why functions have their unique environment.

The local scope is an isolated scope for functions.

The local scope is created when a function is called and is deleted after the execution ends. Each function call creates a new local scope.

Nested local scopes

Consider a case when you define a function inside another function:

In the example above, we have the function outer with a local variable outer_variable. The subfunctions first_inner and second_inner can use the outer_variable but can't change it. Inside the second_inner function, we are trying to modify outer_variable, which gives us an error.

In the outer local scope, we have two isolated scopes for each subfunction (first_inner and second_inner):

The inner scopes can use the outer scopes:

FunctionAvailable scopes
outer()built-in, global, outer() local
first_inner()built-in, global, outer() local, first_inner() local
second_inner()built-in, global, outer() local, second_inner() local


The outer() local scope is named non-local scope for the functions first_inner() and second_inner(). The non-local scopes will be described in the next chapter.

Everything was clear?

Section 1. Chapter 3