What is `if __name__ == "__main__":` for?
BeginnerConceptLanguage essentials & functions
Answer
When a file is run directly, __name__ is "__main__"; when imported, it is the module name. The guard lets a file be both an importable module (for tests and reuse) and a script, without running side effects on import. It is also required on Windows and macOS (spawn start method) for multiprocessing, otherwise child processes re-import and re-execute your top-level code.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner