How to Access Variables Outside a Function in Python?

In this tutorial, I will explain how to access variables outside a function in Python. As a developer working on various projects, I came across a scenario where I needed to access variables outside a function. After researching I found some ways to accomplish this task. By the end of this post, you will clearly understand how to work with global, local, and nonlocal variables in Python, complete with practical examples.

Variable Scope in Python

Before getting into the examples, it’s crucial to understand the concept of variable scope. In Python, the scope of a variable determines where that variable can be accessed or modified. There are four types of scopes in Python:

  1. Local Scope: Variables declared inside a function.
  2. Enclosing Scope: Variables in the local scope of enclosing functions.
  3. Global Scope: Variables declared at the top level of a script or module.
  4. Built-in Scope: Names preassigned in the built-in namespace.

These scopes follow the LEGB rule, which stands for Local, Enclosing, Global, and Built-in.

Read How to Use the arange() Function in Python?

Global Variables in Python

Global variables in Python are defined outside of any function and can be accessed from any function within the same module. Here’s an example:

# Global variable
city = "New York"

def print_city():
    print(f"The city is {city}")

print_city() 

Output:

The city is New York

You can see the output in the screenshot below.

Access Variables Outside a Function in Python

In the example above, the variable city is global and can be accessed by the print_city function.

Check out How to Use the insert() Function in Python?

Modify Global Variables in Python

To modify a global variable inside a function, you need to use Python’s global keyword. Here’s an example:

# Global variable
population = 8000000

def update_population():
    global population
    population += 100000

update_population()
print(f"The updated population is {population}") 

Output:

The updated population is 8100000

You can see the output in the screenshot below.

How to Access Variables Outside a Function in Python

In this case, the global keyword allows the function update_population to modify the global variable population.

Read How to Use the strip() Function in Python?

Local Variables in Python

Local variables are defined within a function and can only be accessed within that function in Python. Here’s an example:

def calculate_area(length, width):
    area = length * width
    return area

# Trying to access 'area' outside the function will result in an error
print(calculate_area(5, 10))

Output:

50

You can see the output in the screenshot below.

Access Variables Outside a Function in Python Local Variables

Attempting to access the variable area outside the calculate_area function will result in an error because it is a local variable.

Check out How to Use the trim() Function in Python?

Nonlocal Variables in Python

Nonlocal variables in Python are used in nested functions and allow you to modify a variable in the enclosing scope. Here’s an example:

def outer_function():
    state = "California"

    def inner_function():
        nonlocal state
        state = "Nevada"
        print(f"Inner state: {state}")

    inner_function()
    print(f"Outer state: {state}")

outer_function()

Output:

Inner state: Nevada
Outer state: Nevada

You can see the output in the screenshot below.

Access Variables Outside a Function in Python Nonlocal Variables

In this example, the nonlocal keyword allows the inner_function to modify the variable state in the outer_function.

Read How to Use the Floor() Function in Python?

Example: Manage a Database Connection

Let’s consider a more practical example where you might need to manage a database connection in a Python script. Assume you are working on a project for a company based in San Francisco.

import sqlite3

# Global variable for database connection
db_connection = None

def connect_to_database():
    global db_connection
    db_connection = sqlite3.connect('company.db')
    print("Database connected")

def close_database():
    global db_connection
    if db_connection:
        db_connection.close()
        print("Database closed")

def execute_query(query):
    global db_connection
    cursor = db_connection.cursor()
    cursor.execute(query)
    db_connection.commit()
    print("Query executed")

# Using the functions
connect_to_database()
execute_query("CREATE TABLE IF NOT EXISTS employees (id INTEGER PRIMARY KEY, name TEXT, position TEXT)")
close_database()

In this example, the db_connection variable is global and is used across multiple functions to manage the database connection.

Check out How to Use the round() Function in Python?

Common Issues and Solutions

One common issue developers face is the “UnboundLocalError”. This error occurs when you try to modify a global variable without declaring it as global inside a function. Here’s an example:

counter = 10

def increment_counter():
    counter += 1  # This will raise an UnboundLocalError
    print(counter)

increment_counter()

To fix this issue, use the global keyword:

counter = 10

def increment_counter():
    global counter
    counter += 1
    print(counter)

increment_counter()  # Output: 11

Read How to Use the repeat() Function in Python?

Best Practices for Using Global Variables in Python

While global variables can be useful, they should be used sparingly. Overuse of global variables can make your code harder to understand and maintain. Here are some best practices:

  1. Minimize the use of global variables: Use local variables whenever possible.
  2. Encapsulate global variables: Use functions or classes to manage the global state.
  3. Document your global variables: Comment on the purpose and usage of global variables.

Check out How to Use the ceil() Function in Python?

Conclusion

In this tutorial, I have explained how to access variables outside a function in Python. I discussed the variable scope, global variables, modify global variables, local variables, and nonlocal variables in Python. I also discussed practical examples , common issues and solutions, and some best practices for using global variables.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.