Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and 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.
info = "Important info" def func(): info = "Damaged info" func() print(info)
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:
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()
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:
Function | Available 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 functionsfirst_inner()
andsecond_inner()
. The non-local scopes will be described in the next chapter.
Thanks for your feedback!