Why is Python running my module when I import it, and how do I stop it?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When you import a Python module, Python executes all the top-level code in that file — not just function and class definitions, but also print statements, function calls, and any other executable code. This is by design: Python needs to execute the module to define its functions, classes, and variables. To prevent code from running on import, wrap it in if __name__ == "__main__":. This guard checks whether the module is being run directly (as a script) or being imported, and only executes the protected code when run directly.
The Problem
Running main.py prints both messages because import mymodule executes every line in mymodule.py, including the print calls.
The Fix: if __name__ == "__main__":
How __name__ Works
Common Use Cases
Script with Importable Functions
Running Tests
Entry Point for Packages
What Top-Level Code Is Safe to Leave Unguarded
Common Pitfalls
- Putting initialization code outside the guard: Any
print(),input(), database connection, file write, or network request at the top level runs on every import. Move side-effect-producing code insideif __name__ == "__main__":. - Importing a module that modifies global state: Some libraries print messages, configure logging, or modify
sys.pathat import time. If you import such a module, its side effects execute immediately. Check third-party module documentation for import-time behavior. - Forgetting the guard when using
argparse:parser.parse_args()readssys.argvand fails when imported in contexts like Jupyter or test runners. Always put argument parsing inside the__name__guard. - Assuming functions are not defined on import: Function and class definitions (
def,class) are executed on import — they create function/class objects in the module's namespace. This is the intended behavior. Only guard the code that calls those functions. - Using
__name__guard in Jupyter notebooks: In a Jupyter notebook,__name__is always"__main__"for every cell, so the guard does not help. Structure notebook code differently — use function calls instead of top-level executable code.
Summary
- Python executes all top-level code in a module when it is imported — including prints, function calls, and variable assignments
- Use
if __name__ == "__main__":to protect code that should only run when the file is executed directly as a script __name__is"__main__"when run directly and the module's name when imported- Function and class definitions should stay at the top level (outside the guard) so they are importable
- Guard argument parsing, CLI output, tests, and any other side-effect-producing code
- For packages, use
__main__.pyto define the entry point forpython -m mypackage

