Use the Python Main Guard
Core idea
When Python runs a file as the entry point, its __name__ is "__main__". When the same file is imported normally, its name is the import name. Put command-line actions behind a main guard to keep the reusable definitions importable without those actions.
Run a script directly
Save the following code as bm_report.py and run python bm_report.py from the new directory. Use a fresh directory for each example.
def main(): print("Ready")
if __name__ == "__main__": main()Output: Ready, because this file is the entry point.
Import the guarded module
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_report.py
def main(): print("Ready")
if __name__ == "__main__": main()Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
Output: bm_report only. The guard skips the main call; the function is still available.
Separate a calculation from its display
In a new empty directory, create the parent folders and these files (an empty file is marked by its filename alone):
bm_cost.py
def total(price, count): return price * count
if __name__ == "__main__": print(total(3, 5))Save the following code as run.py and run python run.py from the new directory. Use a fresh directory for each example.
from bm_cost import totalprint(total(6, 2))Output: 12. The guarded demo is not printed during import.
Common mistake
The guard does not prevent every top-level statement from executing. A print, function call or other side effect outside the guard still runs when the module initializes.
Practice
Add a top-level print outside the guard in your own sample module. Run it directly and import it in a fresh process. Move the print inside main and compare.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Predict entry-point behavior
Check your understanding of main guard.
What does this standalone script print?
if __name__ == "__main__": print("Start")A module named bm_report is imported normally. What is its __name__?
Where should a demonstration call go if it must not run on normal import?
What happens to function definitions outside the guard during import?