Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Local Scope | Scopes
Mastering Python: Closures and Decorators
course content

Зміст курсу

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

Local 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

Note

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.

Все було зрозуміло?

Секція 1. Розділ 3
We're sorry to hear that something went wrong. What happened?
some-alt