The main guard
Not met yet
When a file is run directly, its __name__ is "__main__"; when it's imported, __name__ is the module's name. So the code under if __name__ == "__main__": runs only when the file is the program itself. It's the place for quick checks and demos, which a program importing the file doesn't want to see. The functions above it are still there for importers.
Try it
main.pydef is_open(hour):
return 9 <= hour < 17
if __name__ == "__main__":
print(is_open(10))
print(is_open(17))
Output
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks __name__ holds the file's name even when the file is run directly, rather than "__main__".
- Thinks __name__ has to be defined by the program before it can be used.
- Thinks the main guard stops importers from using the functions defined in the file.
Where it comes up
- Opening Hours Module
- Word Counter and Text Analyser
- Quiz App
- Bank Account System
- Library Manager
- Command-Line To-Do Tool
- Log Streamer
- Timing and Retry Decorators
- Personal Finance App
- Weather App
- Speed Tester
- Task Scheduler
- NumPy Grade Book
- Census Explorer
- Data Cleaning Pipeline
- Census Pivot Tables
- Weather History Dashboard
- Summary Statistics Report
- Statistics Toolkit
- Linear Algebra Lab
- Calculus for ML
- Data Story
- House Price Predictor
- Exam Score Model
- Diabetes Risk Classifier
- Iris and Penguins Classifier
- Loan Approval Tree
- Customer Segmentation
- Model Evaluation Clinic
- Fishing Forecast
- Weather Data Investigation
- Paper Reproduction
- Arcade Catch Game
- Your Own Project