Sub topic 5
Scripts versus modules and the __main__ guard
This chapter assumes you can write functions, run python file.py from a terminal, and use a basic import statement. It covers how one file can act as a program and as a library, and how the __main__ guard keeps those roles apart.
One file, two roles
A Python file can be used in two ways:
- As a script, which you run directly:
python greet.py. - As a module, which another file imports:
import greet.
Python runs the same top-to-bottom code in both cases. What differs is the value of the module's __name__ variable. Python sets __name__ before it runs the file's code.
| How the file is loaded | Value of `__name__` |
|---|---|
| `python greet.py` | `"__main__"` |
| `python -m greet` | `"__main__"` |
| `import greet` | `"greet"` |
| `import shapes.circle` | `"shapes.circle"` |
| Interactive prompt or `python -c "..."` | `"__main__"` |
The module Python starts with is always registered under the name __main__. Every other module is registered under its dotted import name.
The guard
The standard idiom compares __name__ with the string "__main__":
# greet.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("world"))Running the file directly prints the greeting:
$ python greet.py
Hello, world!Importing it prints nothing, because __name__ is "greet" and the if body is skipped:
$ python -c "import greet; print(greet.greet('Ada'))"
Hello, Ada!The def statement runs in both cases, so greet is defined either way. Only the guarded block depends on how the file was started.
Why you want the guard
Without the guard, importing a file runs everything in it. That causes three problems:
- Unwanted side effects. Importing a module that prompts for input, opens a network connection, or deletes files is surprising and often harmful.
- Untestable code. A test runner imports your module to call its functions. If the import also runs the program, the tests become slow or hang.
- No reuse. You cannot borrow one helper from a script without also running the whole script.
The guard lets one file serve as both a library of functions and a command-line tool.
A practical layout: `main()` plus the guard
Keep the guarded block as small as possible. Put the program logic in a main function, and let the guard only call it:
# wordcount.py
import sys
def count_words(text):
return len(text.split())
def main(argv=None):
argv = sys.argv[1:] if argv is None else argv
if len(argv) != 1:
print("usage: python wordcount.py FILE", file=sys.stderr)
return 2
with open(argv[0], encoding="utf-8") as f:
print(count_words(f.read()))
return 0
if __name__ == "__main__":
sys.exit(main())This layout has several benefits:
maintakesargvas a parameter, so a test can callmain(["sample.txt"])without touchingsys.argv.mainreturns an exit code, andsys.exitpasses it to the shell. Returning2for bad usage follows the common convention.- Variables created inside
mainare local. If you put the same code directly under theif, those variables become module globals, and functions in the module could use them by accident.
Another file can now reuse the counting logic:
# report.py
from wordcount import count_words
print(count_words("one two three"))Running python report.py prints 3, and wordcount.py does not try to read a file.
What the guard does not do
The guard only protects the code inside it. Anything at module level outside the guard still runs on import:
# noisy.py
print("loading noisy") # runs on every import
def helper():
return 42
if __name__ == "__main__":
print("running as a script")import noisy prints loading noisy. Module-level code is for definitions, constants, and cheap setup. Move slow or effectful work, such as reading files or connecting to a database, into functions that callers invoke on purpose. Chapter material on import-time side effects returns to this point later.
The double-import trap
A module loaded as a script is registered as __main__, not under its file name. If some other module later does import yourfile, Python does not find yourfile in sys.modules. It runs the file a second time and creates a separate module object.
You can see this with a file that imports itself:
# twice.py
print("executing, __name__ =", __name__)
import twiceRunning python twice.py prints:
executing, __name__ = __main__
executing, __name__ = twiceThe two copies are different objects, with separate copies of every global. A class defined in the file exists twice, so isinstance checks between the copies fail, and module-level state such as a counter or a registry is duplicated. In real code this usually appears through a cycle: script a.py imports b, and b imports a.
The usual fix is to keep the entry-point file thin. Put the real code in an importable module, and have the script import it.
Related details
__file__. A module loaded from a file has a__file__attribute with its path. It is not defined at the interactive prompt, so code that reads it will fail there.__main__.py. A package can contain a file named__main__.py, which runs when you start the package withpython -m package. That mechanism belongs to a later chapter onpython -m.- Import-time
__name__use. Some code logs withlogging.getLogger(__name__). That relies on the same rule: the logger is named after the module, or__main__when run as a script. - Not a security boundary. Anyone can set
__name__themselves withrunpy.run_path(..., run_name="__main__"). The guard organizes code. It does not protect it.
Quick checklist
- Put definitions at module level, and put program behavior inside
main(). - Call
main()from anif __name__ == "__main__":block, and pass its result tosys.exit. - Do not run top-level code that has side effects.
- Do not import a file from elsewhere if you also run it directly as a script.
Exercise
A file stats.py contains print("loaded") at module level, a function mean(xs), and a guarded block that prints mean([1, 2, 3]). What is printed by python stats.py, and what is printed by python -c "import stats"?
Show answer
python stats.py prints loaded and then 2.0 (or the value mean returns), because __name__ is "__main__" and the guarded block runs. python -c "import stats" prints only loaded. The module-level print runs on import, but the guarded block is skipped because __name__ is "stats".
Exercise
Why is sys.exit(main()) with def main(argv=None) easier to test than putting the same code directly under the if __name__ == "__main__": line?
Show answer
A test can import the module and call main(["arg"]) directly, passing arguments and checking the returned exit code, without launching a subprocess or changing sys.argv. Code placed directly under the if only runs when the file is started as a script, and its variables become module globals.