Lesson · Modules, Packages & Imports
The __main__ Pattern
55 min readThe __main__ Pattern
The `__main__` pattern separates reusable definitions from script entry behavior. It lets the same file be imported safely and also executed directly.
Learning goals
- Explain what
__name__holds in both invocation modes and how the guard reads it. - Separate reusable definitions from entry behavior so importing the file runs no application code.
- Run the same file directly and as an imported module, and predict the difference.
- Move command-line parsing and exit calls inside a
main()function where they belong. - Explain why guarding the entry point makes the module testable.
Mental model
The whole pattern is this fork: the interpreter sets __name__ according to how the file was reached, and the guard turns that one string into a decision about whether to start the application. Everything above the guard is a library of names; everything inside it is orchestration.
Mental model
read it top to bottom
python file.py → __name__ == "__main__" → the guard runs main() import file → __name__ == "file" → definitions only, no work
Core idea
The __main__ pattern is one if that asks how this file was started. When the file is executed directly, __name__ is "__main__" and the guard runs the entry function; when the file is imported, __name__ is the module's own name and only the definitions are created. That split lets one file be both a testable library and a command-line program, and it keeps importers free of the program's side effects.
Imported vs executed module
The same file plays two roles: imported, its __name__ is the module name and the __main__ guard stays false; executed with python file.py, its __name__ is "__main__" and the guard runs. Code that must not fire on import belongs under that guard.
Entry points
An entry point is the callable or module location where an application starts. Separating it from reusable logic makes testing and packaging easier.
Script organization
Put reusable functions and classes above a small entry function, then call that entry function under the __main__ guard. This prevents command-line behavior from running during import.
Avoiding import side effects
Importing a module executes its top level, so any statement written outside functions runs in every importing process. Keeping the top level to definitions, constants, and the guarded entry call means an import only creates names and never starts work.
Walkthrough
def main():holds the entry behavior as an ordinary function, so the work is defined but not performed at definition time.if __name__ == "__main__":reads the current module's name string:python lesson.pysets it to"__main__", so the condition is true, whileimport lessonsets it tolesson, so the condition is false.- The guarded
main()call is what printsapplication starts here; importing the same file prints nothing while still exposingmainfor tests. - Predict before running: which lines execute under
python file.py, and what changes when the file is imported instead.
Experiments to try
- Run the file directly, then import it from a second file; record which mode prints
application starts hereand which stays silent. - Add
print(__name__)before the guard and compare the values across direct execution and import. - Move the
main()call out of the guard so it runs unguarded, import the file, and explain why aprintfires on import now. - Give
main()a return value and call it from an importing file; note that direct execution discards the value while a caller can assert on it.
Common mistakes
- Leaving application code at the top level: importing the file starts the work before the importer can call anything, which also breaks tests that only need the functions.
- Writing the guard as
if __name__ == "main":: the interpreter sets__name__to"__main__"with leading and trailing double underscores, so the comparison never matches and the entry function silently never runs. - Calling
main()both under the guard and at the bottom of the file: direct execution starts the application twice, which surfaces as duplicated output or double side effects. - Putting
argparse,input(), orsys.exit()at module level: every importer parses arguments that belong to the program or terminates the importing process along with the program.
Practice: Easy
- Save the worked example as
app.py, runpython app.py, and record what prints; then record what prints when another file runsimport app. - Insert
print(__name__)above the guard and compare the value in both invocation modes. - Change the guard to
if __name__ == "main":and explain whypython app.pyprints nothing.
Practice: Medium
- Grow the example into a script that reads one command-line value and prints its square; keep the computation in a function and the input handling under the guard.
- Write a second file that imports the first and calls its function three times; show that no command-line behavior fires.
- Take a small unguarded script and split it into definitions plus a guarded
main(); list everything that moved.
Practice: Hard
- Design a module that serves both roles: an importable library of functions and a
python module.py --checkentry point; keep argument parsing insidemain()so imports never touchsys.argv. - Reproduce the double-run bug by calling
main()at the bottom and under the guard, then fix it and explain what each arrangement does under both invocation modes. - Catch a domain error inside
main()and turn it into an exit code withsys.exit; explain why the guard, not the module top level, is the right place for that call.
Lesson checklist
- I can state what
__name__is in both invocation modes. - I can explain what belongs above the guard and what belongs inside it.
- I can make a file that prints nothing when imported but starts an application when executed.
- I can spot an unguarded entry call and fix the double-run or import side effect it causes.
Remember
The `__main__` pattern turns one file into both a library and a program: definitions and constants at the top, entry behavior inside `if __name__ == "__main__":`. The interpreter decides the branch by setting `__name__` to `"__main__"` for direct execution and to the module name for imports. Keep command-line parsing, exit calls, and application startup inside the guard, because importing a module should never start work.
Interview angles
What is the main purpose of **Imported vs executed module**?+
The same file plays two roles: imported, its __name__ is the module name and the __main__ guard stays false; executed with python file.py, its __name__ is "__main__" and the guard runs. Code that must not fire on import belongs under that guard.
What should you pay attention to when using **Entry points**?+
An entry point is the callable or module location where an application starts. Separating it from reusable logic makes testing and packaging easier.
How does **Script organization** fit into this lesson?+
Put reusable functions and classes above a small entry function, then call that entry function under the __main__ guard. This prevents command-line behavior from running during import.
Why does the guard fail to fire when it is written as `if __name__ == "main":`?+
The guard is an exact string comparison, and the interpreter sets __name__ to "__main__" with the leading and trailing double underscores. "main" never equals it, so the guarded call is skipped and the file runs with no entry behavior.