Python › Modules & Packaging

What does the `if __name__ == '__main__':` idiom accomplish, and why is it important for modules?

Intermediate

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 imported
Real-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.

Common follow-ups: How does this interact with the -m flag for running modules?;What does __name__ equal when run via `python -m package.module`?