The main guard
Allow a module to be imported without executing its demonstration.
On this page
The concept
Module-level statements execute during the first import in a process. That is useful for definitions but surprising when import asks for input or writes a file. The main guard separates definitions from an explicit program entry point.
When a file runs directly, its name is "main". When imported normally, name is its module name. A main function organizes the outer workflow; the guard decides whether to call it. This simple boundary supports both reuse and command-line execution.
Worked example
def add(a, b):
return a + b
def main():
print("Running the module directly.")
print(add(4, 6))
if __name__ == "__main__":
main()Trace the result
- add is defined at module level and can be imported independently.
- main contains demonstration output and a call to add.
- The guard invokes main only during direct execution.
Running the module directly.
10Line-by-line walkthrough
Lines 1–2: def add(a, b):
Define the function add with input names a, b. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 2: return a + b
Evaluate a + b and return that value to the caller. This ends the current function call; subsequent statements on this execution path do not run.
Lines 5–7: def main():
Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.
Line 6: print("Running the module directly.")
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Line 7: print(add(4, 6))
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Lines 10–11: if __name__ == "__main__":
Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.
Line 11: main()
Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.
Common mistake
Putting an unguarded input or storage operation at module level causes that action during import as well.