main guard
The line if __name__ == "__main__": which runs the block beneath it only when the file is run as a program, not when it is imported.
In more detail
Python sets __name__ to "__main__" for the file you run and to the module name for a file being imported. Putting the call to main() under the guard lets the same file be both a script and a reusable module, and lets tests import it safely.
Example
if __name__ == "__main__":
main()Related terms
- main function — By convention, a function called main that holds a program's top-level steps and is called once at the end of the file.
- module — A file of code whose functions, classes and variables other files can use by importing it.
- import statement — A statement that makes code from another module or package available by name in the current file.
Taught in
- Exceptions: try, except, else, finally — Hands-on Python: Complete Video Course & Book
- Modules And The Import System — Hands-on Python: Complete Video Course & Book
- Packages, And Your Own Library — Hands-on Python: Complete Video Course & Book