What does the `if __name__ == '__main__':` idiom accomplish, and why is it important for modules?
Short answer
Every module has a __name__ attribute set to '__main__' if run directly as a script, or to the module's actual name if imported elsewhere.
Advertisement
AModel answer
Every module has a __name__ attribute set to '__main__' if run directly as a script, or to the module's actual name if imported elsewhere. Guarding script-execution code with `if __name__ == '__main__':` lets a file work both as a reusable importable module and as a standalone script, without running its script-only logic (like CLI parsing or test code) when imported by other code.
# mymodule.py
def main():
print('Running as a script')
if __name__ == '__main__':
main() # only runs when executed directly, not when importedReal-world example
A data-processing module exposes reusable functions for import elsewhere, but also includes a `__main__` block so it can be run directly from the command line for quick manual testing.
Likely follow-ups
- How does this interact with the -m flag for running modules?
- What does __name__ equal when run via `python -m package.module`?
Related topics