If you have ever copied a quick demo or a throwaway test into a Python file and then cursed when imports started doing weird things welcome to the world of the main guard. The expression __name__ == "__main__"
is the polite way to say run this code only when the file is executed as the program and not when it is imported as a module.
Python gives every module a built in variable called __name__
. When you run a file directly the interpreter sets that variable to "__main__"
. When another file imports the module Python sets __name__
to the module name instead. The check if __name__ == "__main__"
is a gate that prevents code from running on import.
main
function so the same file works as a library and a script.Replace top level prints with a clear entry point. This pattern is test friendly and plays nicely with importers and test runners.
def main():
print("Running as a script")
# parse args and run program logic here
if __name__ == "__main__":
main()
If you run a module with python -m yourpackage.module
Python will execute it as a script and set __name__
to "__main__"
. That lets packages act as convenient command line tools without rewriting code.
main
.main
function that contains runnable behaviormain()
from inside the guardIn short treat the guard as an on off switch for script behavior. Use it and your modules will behave like polite citizens in the python ecosystem whether you are teaching a tutorial using python main examples or building reusable python modules for production and testing.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.