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 know that import runs a file once and caches it in sys.modules.
One file, two roles
A Python file can run in two ways. You can run it directly as a script, or another file can import it as a module. The code is the same in both cases. What differs is the value of the module's __name__ variable.
- When you run
python greet.py, Python names the module__main__. - When another file runs
import greet, Python names the modulegreet.
# greet.py
def greet(name):
return f"Hello, {name}!"
print("name is", __name__)Running python greet.py prints name is __main__. Running python -c "import greet" prints name is greet.
The guard
Top-level code runs on every import. A script usually has code that should run only when the file is the entry point, such as a demo, a command-line parser, or a test run. Compare __name__ to "__main__" to protect that code:
# greet.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("world"))Running the file prints Hello, world!. Importing greet from another file defines the function and prints nothing.
Common structure
Put the entry-point logic in a function, usually called main, and call it from the guard. Other code and tests can then call main() directly.
# tool.py
import sys
def main(argv):
name = argv[1] if len(argv) > 1 else "world"
print(f"Hello, {name}!")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))sys.exit passes the return value to the shell as the exit status, so 0 means success.
Common errors
- No guard on a script that others import. Importing it runs the demo code, which can print output, open files, or start servers.
- Importing your own script by its file name. If
greet.pyruns as__main__and another module importsgreet, Python loads the file a second time under the namegreet. The module-level code then runs twice, and you get two separate module objects. The cause is that thesys.modulescache is keyed by name, and the same file has two names. - Putting definitions inside the guard. Functions and classes defined there do not exist when the file is imported.
Where this leads
The guard works with python -m package.module, which also sets __name__ to "__main__" but resolves the module through the import system. That form is covered in a later chapter.
Exercise
A file report.py contains print("loading") at top level and a guarded main() call. Another file runs import report. What is printed, and does main() run?
Show answer
It prints "loading", because top-level code runs on import. main() does not run, because __name__ is "report" rather than "_main_", so the guard condition is false.
Exercise
Why does python greet.py followed by an import of greet inside the same program run the file's top-level code twice?
Show answer
The running script is registered in sys.modules as __main__. Importing greet finds no cache entry under that name, so Python loads the same file again as a new module named greet.