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

Course Content

Mastering Python: Closures and Decorators

Mastering Python: Closures and Decorators

1. Scopes
2. Closure
3. Decorators

bookLocal 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.

12345678
info = "Important info" def func(): info = "Damaged info" func() print(info)
copy

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:

123456789101112131415
def outer(): outer_variable = 100 print("Outer:", outer_variable) def first_inner(): print("First inner:", outer_variable) def second_inner(): outer_variabler += 5 print("Second inner:", outer_variable) first_inner() second_inner() outer()
copy

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.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt