Back to Python
2026-01-276 min read

Python globals()

Learn Python globals() step by step with clear examples and exercises.

Title: Python globals() - A full guide for Mastering Global Variables

Why This Matters

Understanding Python's globals() function is crucial for managing global variables, troubleshooting complex programs, and optimizing code efficiency. It allows you to interact with the current global symbol table, making it an essential tool for every Python developer. By learning how to effectively use the globals() function, you will be able to write more flexible and maintainable code.

Prerequisites

Before diving into the globals() function, ensure that you have a solid understanding of the following concepts:

  • Variables and assignments in Python
  • Functions in Python
  • Scope rules in Python (local vs global variables)
  • Basic data structures like lists and dictionaries
  • Importing modules using the import statement

Understanding Variables, Functions, and Scopes

To fully appreciate the importance of the globals() function, it's essential to understand how variables, functions, and scopes work in Python.

Variables

In Python, a variable is a named container for storing data. Variables can be assigned values of various data types, such as integers, floats, strings, lists, or dictionaries.

Functions

A function is a block of code that performs a specific task and can take input (arguments) and return output (results). Functions help organize your code by breaking it into smaller, more manageable parts.

Scopes

In Python, variables have different scopes, which determine their visibility and accessibility within the program. The main scopes are:

  • Global scope: Variables defined at the top level of a module or outside any function belong to the global scope. These variables can be accessed from anywhere in the module.
  • Local scope: Variables defined inside a function belong to the local scope, which is only accessible within that function.
  • Built-in scope: Some variables, like print() and len(), are part of Python's built-in scope and can be accessed from anywhere in your code without needing to be declared.

Core Concept

Introduction to globals()

The globals() function returns a dictionary representing the current global symbol table. This table contains all the names that are defined at the top level of the module or global scope and any imported modules. The globals() function can be used to access, modify, or manipulate global variables within your code.

>>> x = 10
>>> y = 20
>>> globals()
{'x': 10, 'y': 20}

Accessing and modifying global variables

You can access and modify global variables using the globals() function as a dictionary. Here's an example:

def increment_global():
global x
x += 10

x = 5
increment_global()
print(x) # Output: 15

Using globals() within functions

You can also use the globals() function inside a function to access and modify global variables. However, it's generally recommended to declare global variables at the top of the module or at least before calling any functions that might need them.

def increment_global():
for key, value in globals().items():
if key == 'x':
x += 10

x = 5
increment_global()
print(x) # Output: 15

Importing modules with globals()

The globals() function can also be used to import modules and access their contents.

import math

globals().update(math.__dict__)
print(sqrt(2)) # Output: 1.4142135623730951

The locals() function

In addition to the globals() function, Python provides the locals() function, which returns a dictionary representing the current local symbol table (i.e., variables defined within the function). This can be useful for accessing and manipulating local variables within functions.

def example_function():
x = 10
y = 20
locals()

Output: {'x': 10, 'y': 20}

Worked Example

In this example, we will create a simple calculator that uses global variables and the globals() function to perform calculations based on user input.

def get_input():
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
else:
print("Invalid operator. Please use +, -, *, or /.")
return None

global total
total = result
print(f"The result is {total}")

total = 0
get_input()

Common Mistakes

  1. Forgetting to declare global variables: If you try to modify a local variable with the same name as a global one without declaring it as global, Python will create a new local variable, and your changes won't affect the global variable.
def increment():
x = 10 # Local variable x is created, not the global x
global x
x += 1

x = 5
increment()
print(x) # Output: 5
  1. Modifying global variables within a loop: When modifying a global variable inside a loop, make sure to use global x at the beginning of the function to avoid unexpected results due to the creation of local variables.
def increment_in_loop():
for i in range(10):
x = x + 1 # Creating a new local variable x each time
print(x) # Output: None, because local x is out of scope after the loop

global x
x = 5

for i in range(10):
x += 1 # Now modifying the global variable x
print(x) # Output: 16

Common Mistakes (continued)

  1. Not understanding the difference between globals() and locals(): It's essential to understand that globals() returns the current global symbol table, while locals() returns the current local symbol table. Using them incorrectly can lead to unexpected behavior in your code.
  1. Relying too heavily on global variables: While using global variables and the globals() function can be useful in specific situations, it's generally recommended to avoid relying too much on them. A well-structured program should minimize the use of global variables and make use of functions and modules to keep code organized and maintainable.

Practice Questions

  1. Write a Python function that takes two arguments, a and b, and returns their sum using the globals() function.
def add_two_numbers(a, b):
globals()['result'] = a + b
return result

result = 0
print(add_two_numbers(5, 3)) # Output: 8
  1. Modify the simple calculator example to handle exponentiation (using as the operator).
def get_input():
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /, or **): ")
num2 = float(input("Enter second number: "))

if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
elif operator == "**":
result = num1 ** num2
else:
print("Invalid operator. Please use +, -, *, /, or **.")
return None

global total
total = result
print(f"The result is {total}")

total = 0
get_input()
  1. Create a Python program that uses the globals() function to import the random module and generate a random number between 1 and 100.
import random

random_number = random.randint(1, 100)
globals().update(random.__dict__)
print(f"Random number generated: {randint(1, 100)}")

FAQ

Q: What happens if I use globals() inside a nested function?

A: When you use globals() inside a nested function, it still returns the global symbol table of the enclosing function or module. However, be aware that accessing and modifying global variables within nested functions can lead to complex interactions with local variables.

Q: Can I use globals() to access built-in functions like print() or len()?

A: No, the globals() function only returns user-defined names and imported modules. Built-in functions are not part of the global symbol table, so you don't need to use globals() to access them.

Q: Is it a good practice to rely heavily on the globals() function?

A: While using globals() can be useful in specific situations, such as when working with global variables or importing modules, it's generally recommended to avoid relying too much on it. A well-structured program should minimize the use of global variables and make use of functions and modules to keep code organized and maintainable.

Python globals() | Python | XQA Learn