For DevelopersFebruary 27, 2025

How to Set Global Variables Across Modules in Python

Explore a complete guide on setting and managing global variables across multiple Python modules. Covers different approaches, best practices, and unique code examples.

Global variables in Python let you store values that you can access across multiple modules in your project. But if you don’t handle them carefully, they can cause unexpected bugs and hard-to-debug issues. 

In this guide, I’ll walk you through everything you need to know about managing global variables across modules, covering best practices, common mistakes, and practical examples.

Want to work on exciting global projects? Join Index.dev and get matched with top companies for high-paying remote jobs!

 

Understanding Global Variables in Python

global variable is a variable declared at the top level of a script or module, making it accessible throughout that module. But if you need to use the same variable across multiple files, you have to structure your code properly.

Example of a Simple Global Variable in One Module

# config.py
debug_mode = True

This debug_mode variable is accessible in config.py, but if you want to use it across multiple files, you need to import it correctly.

Learn More: Understanding Data Types in Python Programming

 

Using Global Variables Across Multiple Modules

Method 1: Importing a Module Containing Global Variables

One way to use global variables across modules is to define them in a separate module and import them where needed.

Example:

# config.py
app_name = "MyApp"
debug_mode = False

Now, in another module:

# main.py
import config

print(config.app_name)  # Output: MyApp
print(config.debug_mode)  # Output: False

Modifying the Global Variable:

If you change debug_mode inside main.py, it won’t affect config.py unless you explicitly update it:

config.debug_mode = True
print(config.debug_mode)  # Output: True

The change persists only within the current script (main.py), but it doesn't modify config.py itself.

Method 2: Using global Keyword Inside a Function

If you need to modify a global variable inside a function, use the global keyword.

Example:

# settings.py
debug_mode = False

def enable_debug():
    global debug_mode
    debug_mode = True

Then, in another module:

# main.py
import settings

print(settings.debug_mode)  # Output: False
settings.enable_debug()
print(settings.debug_mode)  # Output: True

This ensures that changes made inside enable_debug() reflect across modules.

Method 3: Using importlib.reload() to Force Updates

By default, Python caches imported modules. If a global variable changes in one module, other modules may not see the update unless they reload it.

Example:

# config.py
app_mode = "production"
# main.py
import config
import importlib

print(config.app_mode)  # Output: production

# Modify the variable in config.py manually or through another script
config.app_mode = "development"

# Reload the module to reflect changes
importlib.reload(config)
print(config.app_mode)  # Output: production (because it reloads from the original file)

This is useful if a module is modified dynamically, but in most cases, a structured approach with setter functions is better.

Method 4: Using a Class to Manage Global State

Instead of using raw global variables, you can encapsulate them within a class for better organization.

Example:

# config.py
class Config:
    app_name = "MyApp"
    debug_mode = False
# main.py
import config

print(config.Config.app_name)  # Output: MyApp
config.Config.debug_mode = True
print(config.Config.debug_mode)  # Output: True

Using a class keeps global state organized and prevents unintended overwrites.

Method 5: Using Singleton Pattern

A singleton ensures that only one instance of a configuration object exists.

Example:

# config.py
class GlobalConfig:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(GlobalConfig, cls).__new__(cls)
            cls._instance.debug_mode = False
        return cls._instance
# main.py
from config import GlobalConfig

config1 = GlobalConfig()
config2 = GlobalConfig()

print(config1.debug_mode)  # Output: False
config2.debug_mode = True
print(config1.debug_mode)  # Output: True (Same instance)

The singleton pattern ensures all modules share the same global state.

 

Best Practices for Using Global Variables in Python

  • Avoid modifying imported modules directly. Instead, use setter functions or classes.
  • Use a dedicated config module for shared settings and constants.
  • Consider using environment variables for sensitive or runtime-dependent settings.
  • Reload modules cautiously with importlib.reload() if needed.
  • Use a singleton or class-based approach to avoid conflicts.

Learn More: How to Check If a Set Is Mutually Exclusive in Python

 

Conclusion

Setting global variables across modules in Python can be done in multiple ways, from simple imports to using the singleton pattern. The best approach depends on your use case. If you need a quick solution, using a separate config module works well. If you need better control, using classes or singletons is a cleaner approach.

By following best practices, you can manage global variables effectively without introducing unexpected bugs or performance issues.

For Developers: Level up your career with remote opportunities! Join Index.dev and get matched with top companies worldwide.

For Clients: Need top Python developers? Hire vetted experts from Index.dev in 48 hours with a 30-day risk-free trial!

Share

Ali MojaharAli MojaharSEO Specialist

Related Articles

For EmployersHow Enterprise Engineering Teams Are Structured (Data Study)
Tech HiringInsights
This listicle roundup explains how enterprise engineering teams are structured using real data. It covers leadership models, team size, role ratios, and how companies scale with small teams. It also shows how structure, ownership, and internal tools help improve speed, productivity, and delivery.
Eugene GarlaEugene GarlaVP of Talent
For EmployersHow AI-Native Software Is Changing Every Industry
Software DevelopmentArtificial Intelligence
AI-native apps are software products built with artificial intelligence at their core, where AI drives logic, user experience, and decision-making. From healthcare to finance, they learn, adapt, and improve continuously, delivering faster, smarter, and more secure experiences.
Eugene GarlaEugene GarlaVP of Talent