Why does importing a Python module run its example code?
Quick answer
Importing a module executes its statements. So an example call written at the top level can run as soon as another file imports that module. Keep reusable definitions at module level, put the example or command-line steps in a main() function, and call main() only under if __name__ == '__main__':. That guard distinguishes running the file as the program from importing it. [S1]
The question, the details, the next step.
A practical checklist
Find top-level calls that print output, start a demonstration, or perform other example actions.
Leave reusable functions and classes defined at module level.
Move run-only steps into a
main()function.Call
main()beneathif __name__ == "__main__":.Import a reusable definition from a small caller and check that the example does not run.
A few more useful answers
Will the `main()` function run when another file imports the module?
Not through the guarded call shown here: on import, __name__ is the module name rather than '__main__', so the condition is false. [S1]
Can I keep helper functions outside the guard?
Yes. Put reusable function and class definitions outside the guard. Put the call that starts the example or script inside main(), and call main() under the guard.
Does the guard stop every statement in the file from running on import?
No. It controls the call to main() beneath it. Other unguarded top-level statements still execute when the module is loaded, so keep run-only actions out of that area. [S1]
Sources
References used for this guide.
- [S1] __main__ — Top-level code environment (Python 3.15 documentation) docs.python.org · Checked
