Paul's Python CoursePPC

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.py
def 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