Conteúdo do Curso
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:
number = 15 print("Regular: number =", number) def some_function(): number = 256 print("Function: number =", number) some_function() print("Regular: number =", number)
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.:
number = 2077 string = "Global scope" print(len(string)) def add(first, second): result = first + second return result print(add(25, 13)) print(result) # NameError: no `result` variable 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.
Obrigado pelo seu feedback!