Modules and environments
Main guards and packages
Separate importable definitions from script entry points.
Lesson 41 of 63
Reading: about 1 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
Python sets __name__ to "__main__" for a directly run file and to its module name when imported. Put demo or command-line work behind a main guard. Create report.py and main.py in the same folder, then run python main.py.
Worked example
def label(n):
return f"Total: {n}"
if __name__ == "__main__":
print(label(5))import report
print(report.label(8))Total: 8
Why this works
Importing report defines label but skips the guarded print. A package is a directory of modules; an __init__.py file makes an ordinary package explicit.
Another case
# This file marks tools as a package.def upper(text):
return text.upper()from tools.labels import upper
print(upper("python"))PYTHON
Practice
Run report.py directly after the example. Explain why its output differs from importing it.
Check the practice result
Reveal answer
Direct execution prints Total: 5 from the guarded block; import skips that block.
Try another case
report.py also has print("loading") above its main guard. What does import report display?
Check your answer
Reveal answer
It displays loading. Code outside the guard runs on import; only the guarded block is skipped.
Your progress
Reveal the check answer or reach the end to complete this lesson.