Explain the visibility of global variables in imported modules in Python?

In Python, global variables are module-specific, meaning they exist within the scope of a single module rather than being shared across all modules like in C. Understanding this concept is crucial for managing data across multiple Python files.

Global Variables Are Module-Specific

When you define a global variable in a Python module, it's only accessible within that module. Each module maintains its own global namespace ?

# module1.py (simulated)
counter = 0

def increment():
    global counter
    counter += 1
    return counter

print("Module1 counter:", counter)
Module1 counter: 0

Setting Module Attributes from Outside

You can set attributes on imported modules to create module-specific "global" variables ?

# Simulating module import and attribute setting
class Module1:
    def __init__(self):
        self.counter = 0
    
    def get_counter(self):
        return self.counter

# Simulate: import module1
module1 = Module1()

# Set attribute from outside
module1.counter = 5
print("Updated counter:", module1.get_counter())
Updated counter: 5

Using a Global Configuration Module

For variables shared across multiple modules, create a dedicated configuration module that everyone imports ?

# Simulating global_module.py
class GlobalModule:
    shared_value = None

# Simulating module1.py
class Module1:
    def __init__(self, global_ref):
        self.global_ref = global_ref
    
    def display_value(self):
        print("Shared value:", self.global_ref.shared_value)

# Usage example
global_module = GlobalModule()
module1 = Module1(global_module)

# Set the shared value
global_module.shared_value = 42
module1.display_value()
Shared value: 42

Best Practices

Approach Use Case Pros Cons
Module attributes Single module state Simple, direct Tight coupling
Global config module Multi-module sharing Centralized, clean Extra module needed
Class-based globals Complex state management Organized, testable More overhead

Conclusion

Python's module-specific globals provide better encapsulation than C-style globals. Use module attributes for simple cases, or create a dedicated global configuration module for variables shared across multiple modules.

Updated on: 2026-03-24T17:17:09+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements