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

Taught in

References