What are global, local, and nonlocal scopes in Python
Understand scopes and their usages with examples.
Scope is defined as an area where eligible variables can be accessed. To enforce security, programming languages provide means by which a user can explicitly define these scopes.
#more
It is important to understand the use of scopes and how to deal with them. In this article, we will see what are the scopes available in Python and how to work with them.
1. Global scope¶
Any variable defined outside a non-nested function is called a global. As the name suggests, global variables can be accessed anywhere.
Example:¶
side = 5 # defined in global scope
def area():
return side * side
def circumference():
return 4 * side
print(f"Area of square is {area()}")
print(f"Circumference of square is {circumference()}")
Output:
Area of square is 25
Circumference of square is 20
When a function tries to manipulate global variables, an UnboundLocalError is raised. To overcome this the global variable is redefined inside the function using global
keyword. In this way a user can modify global variables without errors.
Example:¶
Without global keyword
side = 5
def multiply_side(factor):
side *= factor
multiply_side(7)
print(f"Side length is {side}")
Output:
UnboundLocalError: local variable 'side' referenced before assignment
With global keyword
side = 5
def multiply_side(factor):
global side
side *= factor
multiply_side(7)
print(f"Side length is {side}")
Output:
Side length is 35
2. Local scope¶
By default, variables defined inside a function have local scope. It implies that local scope variables can be accessed only inside the parent function and nowhere else.
Local variables are destroyed as soon as the scope ceases to exist.
Example:¶
side = 5
def area():
square_area = side * side # local scope
print(square_area)
Output:
NameError: name 'square_area' is not defined
3. Nonlocal scope¶
Nested functions introduce a new type of scope called as nonlocal
scope. When a nested function wants to share the local scope of parent functions, nonlocal
keyword is used.
In such cases, declaring parent function variables as global
does not work.
Example:¶
Without using nonlocal
keyword
side = 5
def half_area():
area = side * side
def divide():
area /= 2
divide()
return area
print(half_area())
Output:
UnboundLocalError: local variable 'area' referenced before assignment
Using nonlocal
keyword:
side = 5
def half_area():
area = side * side
def divide():
nonlocal area
area /= 2
divide()
return area
print(half_area())
Output:
12.5
FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*