Python The __main__ Guard
The __main__ guard is an if line that runs code only on a direct run. The line tests __name__ against "__main__".
Run directly, the name is __main__
Save this line in a file and run the file. Python reports the special name.
print(__name__)Imported, the name is the module name
start.py does nothing but import small. The print inside small still runs, once.
# small.py
print(__name__)
# start.py
import smallThe guard in action
main() holds the work. The guard calls main() only when this file runs directly.
def main():
print("playing")
if __name__ == "__main__":
main()Example
# guessing.py
import random
def play():
random.seed(7)
answer = random.randint(1, 10)
guess = int(input("Guess a number from 1 to 10: "))
if guess == answer:
print("You got it!")
else:
print(f"Sorry, the answer was {answer}.")
def main():
play()
if __name__ == "__main__":
main()Key points
- __name__: a variable that Python sets in every module
- A file run directly gets __name__ equal to "__main__"
- An imported file gets __name__ equal to its own module name
- Use if __name__ == "__main__": to mark code that runs only on a direct run
- Use a main() function to hold the starting steps of a program
- Use python3 -m name to run a module by its name.
- Python finds it the same way import does
- Multiprocessing starts helper processes that import your file again.
- The multiprocessing lesson covers helper processes.
- The guard stops each helper from starting the whole program again
In this example, guessing.py defines play() and main() and calls nothing at the top level. The guard at the bottom calls main() only when the file runs as the main program. The run uses python3 -m guessing, inside the folder that holds guessing.py. The input comes from a file named input.txt, fed in with python3 -m guessing < input.txt. That file holds exactly one line: 6. random.seed(7) makes the hidden answer 6 on every run, so the guess wins. The prompt and the win message share one line. Input read from a file is not echoed back. Importing guessing instead would print nothing and start no game.
Note
Importing a guarded module is quiet.
Nothing runs until you call one of its functions yourself.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A module should only define functions when imported, but act when run directly. Which line does that job?