Course Content
Mastering Python: Closures and Decorators
Mastering Python: Closures and Decorators
What are scopes?
The scope is an environment that stores variables, functions, and other objects in a program.
Let's consider the example:
Code Description
number
:- Global Scope: The variable
- Local Scope (Function Scope): Inside the function
number
is defined outside of any function, at the top level of the code. This makes it a global variable. The global scope allows this variable to be accessible from anywhere within the code, including inside functions.The first
print
statement accesses the global variable number
and prints its value, which is 15
.some_function()
, a new variable number
is defined. This variable has a local scope, meaning it is only accessible within the function and does not affect the value of the global number
variable.The
print
statement inside some_function()
accesses the local variable number
and prints its value, which is 256
.After calling the function
some_function()
, the global number
variable remains unchanged.
The number
variable in the regular code and the number
in the some_function
have the same name but are different variables because they are placed in different scopes.
Scope Types
- Built-in
- Global
- Non-local (Enclosing)
- Local
Built-in Scope
This is a scope of Python built-in tools. For example, the built-in len()
function. You can use this function everywhere in your code.
Global Scope
It's the main scope of your code. This scope contains the variables, functions, and other objects you define.
Non-local (Enclosing) Scope
The non-local scopes are scopes between global and local scopes. The non-local scope can be enclosed and transformed into the enclosing scope. It will be described in the next section.
Local Scope
This scope is used for functions. Every function has a unique scope that deletes after the function executes.
How do scopes work?
Let's take a look at an example and analyze it.:
Code Description
add()
, a variable result
is defined. This variable has a local scope, meaning it is only accessible within the function and does not exist outside of it.When attempting to print the
result
variable outside the add()
function, a NameError
is raised. This is because result
is a local variable, and it doesn't exist in the global scope.
Here the global scope has the variables number
and string
and the add()
function.
The len()
and print()
functions are used from the built-in scope.
The add()
function has a local scope with the variables first
, second
, and result
. Arguments are variables defined inside the function, and the received data assign to these variables.
Everything was clear?