Script Entry Points
Use a guarded main function when a Python file must be both safe to import and able to start a script workflow.
A reusable module should define functions without starting a complete workflow when another file imports it. A script, however, needs a clear place to begin. Python's conventional entry-point pattern supports both uses.
This is a reference page. Chapter 8 does not require the pattern, but you will see it in Python projects and documentation.
Put the workflow in main
Python sets the special name __name__ differently in two situations:
- When this file is run as a script,
__name__is"__main__", somain()runs. - When another file imports it as a module,
__name__is the module's name, so the guarded call does not run.
The guard does not make a function reusable. Separating the calculation from file paths and printing does that. The guard only controls whether the script starts its workflow.
Running a module
Python can also run a module by its import name:
python -m report_app
In that case Python finds report_app as a module and runs it with __name__ set to "__main__". Use this form when a project's instructions define a runnable module. Do not add it merely to make a small one-file exercise look larger.
Keep reusable definitions safe to import. Add a guarded main() only when a file also owns a script workflow.