Python Language Idioms Test for "__main__" to avoid unexpected code execution

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

It is good practice to test the calling program's __name__ variable before executing your code.

import sys

def main():
    # Your code starts here

    # Don't forget to provide a return code
    return 0

if __name__ == "__main__":
    sys.exit(main())

Using this pattern ensures that your code is only executed when you expect it to be; for example, when you run your file explicitly:

python my_program.py

The benefit, however, comes if you decide to import your file in another program (for example if you are writing it as part of a library). You can then import your file, and the __main__ trap will ensure that no code is executed unexpectedly:

# A new program file
import my_program        # main() is not run

# But you can run main() explicitly if you really want it to run:
my_program.main()


Got any Python Language Question?