Python Variable Scope (30/100 Days of Python)

Martin Mirakyan
5 min readJan 31, 2023

--

Day 30 of the “100 Days of Python” blog post series covering variable scopes

In Python, a variable scope refers to the region of the program where a particular variable is accessible and can be used. Understanding scopes is crucial for writing organized and efficient code, as it allows you to keep your variables organized and avoid naming collisions.

There are two types of scopes in Python: global and local.

  1. Global scope: Variables declared outside of any function or class are considered to be in the global scope. These variables can be accessed from anywhere in the program and are not limited to any particular function or class.
  2. Local scope: Variables declared inside a function or class are considered to be in the local scope. These variables are only accessible within the function or class and cannot be accessed from outside

As an example, one might add two variables from global and local scope together in a function:

x = 10 # global scope

def add_numbers():
y = 20 # local scope
result = x + y
print(result)

add_numbers() # 30

It is important to note that variables with the same name can exist in both the global and local scopes, as long as they are used within their respective scopes.

If you want to access a global variable from within a function, you can use the global keyword:

x = 10        # global scope

def add_numbers():
global x
x += 7 # access the global variable x
print(x)

add_numbers() # 17

When working with nested scopes, the innermost scope takes precedence over the outer scopes. In other words, if a variable with the same name exists in both the inner and outer scopes, the inner scope’s variable will be used:

x = 10             # global scope

def outer_function():
x = 20 # outer local scope
def inner_function():
x = 30 # inner local scope
print(x)
inner_function()

outer_function() # prints 30

nonlocal Keyword

The nonlocal keyword in Python is used to indicate that a variable is in an outer, but not global, scope. This keyword allows you to modify a variable in an outer local scope within a nested function:

def outer_function():
x = 10 # outer local scope
def inner_function():
nonlocal x # access the x in outer local scope
x = x + 10 # modify the x in outer local scope
print(x)
inner_function()

outer_function() # prints 20

In the example above, the inner_function is defined within the outer_function. The outer_function has a variable x with a value of 10 in its local scope. Within the inner_function, we use the nonlocal keyword to access and modify the variable x in the outer local scope. The output of the program will be 20, which indicates that the variable x in the outer local scope has been successfully modified.

It’s important to note that the nonlocal keyword can only be used to modify variables in outer local scopes and not in the global scope. If you want to modify a variable in the global scope, you should use the global keyword instead.

Example of the global Keyword in Action

Suppose you are creating a program that keeps track of the number of times a button has been clicked on a website. To do this, you have a variable count that stores the number of clicks, which is defined in the global scope.

count = 0          # global scope

def increment_count():
global count # access the global variable count
count += 1 # increment the value of count
print(count)

# Button click event handler
def on_click():
increment_count()

In this example, the increment_count function increments the value of the count variable whenever the button is clicked. To access the count variable from within the function, we use the global keyword. This allows us to modify the value of the global variable count and keep track of the number of button clicks throughout the entire program.

Without the global keyword, the increment_count function would create a new local variable count instead of modifying the global count, and the button click count would not be properly tracked.

Common Mistakes When Working With global and nonlocal Variables in Python and How to Avoid Them

1. Confusing the global and nonlocal keywords: It's important to understand the difference between the global and nonlocal keywords and when to use each one. The global keyword is used to access and modify global variables, while the nonlocal keyword is used to access and modify variables in outer local scopes within nested functions. Misusing these keywords can lead to unexpected behavior and unexpected changes to different variables.

2. Naming collisions: To avoid naming collisions between global variables and local variables with the same name, it’s a good practice to use unique and descriptive names for your variables. Additionally, you can use the global and nonlocal keywords to explicitly indicate the scope of the variable you're accessing:

# Avoid naming collisions by using descriptive names
count = 0 # global counter
def increment_count(): # A function that should increment the counter
count = count + 1 # local variable with the same name
print(count)

increment_count() # UnboundLocalError: local variable 'count' referenced before assignment

3. Unintended modification of global variables: When you modify a global variable within a function, it can have unintended consequences for other parts of your program that rely on that variable. To avoid this, it’s a good practice to use local variables whenever possible and to limit the use of global variables to situations where it’s absolutely necessary.

4. Forgetting to declare global or nonlocal variables: If you forget to declare a variable as global or nonlocal before modifying it, Python will treat it as a local variable and create a new variable with the same name in the local scope. To avoid this, make sure to always use the global or nonlocal keyword when accessing or modifying variables in global or outer local scopes.

What’s next?

--

--

Martin Mirakyan
Martin Mirakyan

Written by Martin Mirakyan

Software Engineer | Machine Learning | Founder of Profound Academy (https://profound.academy)

No responses yet