Python module entry points
- Version
- 3.14
- Since
- 2.4
- Review
- Draft
Summary#
Python sets __name__ to "__main__" in a file run as a script or a module run with -m. Guard the call to main() so importing the module skips that call. Running a package with -m executes its __main__.py.
Syntax#
if __name__ == "__main__":
main()
python reports/core.py
python -m reports.core
python -m reports
Example#
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
package = Path(directory) / "reports"
package.mkdir()
(package / "__init__.py").write_text("", encoding="utf-8")
(package / "core.py").write_text(
'def main():\n print("report ready")\n\n'
'if __name__ == "__main__":\n main()\n',
encoding="utf-8",
)
(package / "__main__.py").write_text("from .core import main\nmain()\n", encoding="utf-8")
for args in (
["-c", "import reports.core; print('import complete')"],
["reports/core.py"],
["-m", "reports.core"],
["-m", "reports"],
):
subprocess.run([sys.executable, "-E", "-B", "-S"] + args, cwd=directory, check=True)
Expected output#
import complete
report ready
report ready
report ready
Common mistakes#
Pass a dotted import name to -m without .py. Run from the directory containing the package or install the package first. If the module uses relative imports, use -m so Python supplies the package context that direct file execution lacks.
Version applicability#
Python 2.4 introduced -m for top-level modules, and Python 2.5 added support for dotted module names. In Python 3, running a package's __main__.py via -m requires 3.1 or later. The full example needs Python 3.5 for Path.write_text and subprocess.run.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0