Last modified: May 10, 2025 By Alexander Williams
Managing Import Side Effects in Python
Python imports can sometimes cause unexpected side effects. These can slow down your app or create bugs. This guide explains how to manage them.
Table Of Contents
What Are Import Side Effects?
Import side effects happen when importing a module runs code unexpectedly. This can include:
- Slow initialization code
- Global variable changes
- External connections being made
Understanding these helps write cleaner Python code. Learn more in our Python Import System Internals Explained guide.
Common Import Side Effect Examples
Here's a simple module with side effects:
# module_with_side_effects.py
print("This runs when imported!")
database_connection = open_database() # Creates connection on import
def useful_function():
return "Actual useful work"
The print and database connection happen at import time. This may not be what you want.
How to Avoid Import Side Effects
Follow these best practices to minimize problems:
1. Move Code into Functions
Put initialization code in functions rather than at module level:
# better_module.py
database_connection = None
def init_database():
global database_connection
print("Initializing when needed")
database_connection = open_database()
2. Use Lazy Loading
Delay expensive operations until needed. The Python Runtime Module Loading guide shows advanced techniques.
3. Use if __name__ == "__main__"
Protect test code from running on import:
if __name__ == "__main__":
# This only runs when file is executed directly
run_tests()
Testing for Import Side Effects
To check for side effects:
import module_to_test
# Check if anything unexpected happened
Or use dynamic imports with importlib
as shown in our Dynamic Imports in Python guide.
Real-World Example: Fixing Side Effects
Here's how to refactor a module with side effects:
# Before (with side effects)
config = load_config() # Runs on import
# After (fixed)
_config = None
def get_config():
global _config
if _config is None:
_config = load_config()
return _config
Conclusion
Managing import side effects is key to writing clean Python code. Move initialization code into functions. Use lazy loading patterns. Test your imports.
Following these practices will make your applications more predictable and efficient. Always think about what happens when your modules get imported.