You’ve learned what the if __name__ == "__main__"
idiom does in Python. It allows you to write code that executes when you run the file as a script, but not when you import it as a module. It’s best to use it when you want to collect user input during a script run and avoid side effects when importing your module—for example, to unit test its functions.
You also got to know some common but suboptimal use cases and learned about better and more idiomatic approaches that you can take in those scenarios. Maybe you’ve accepted Python’s name-main idiom after learning more about it, but if you still dislike it, then it’s good to know that you can probably replace its use in most cases.
For further investigation, check out:
- 📰 How to Run Your Python Scripts
- 🎬 Running Python Scripts
- 📰 Python Modules and Packages – An Introduction
- 🎬 Python Modules and Packages: An Introduction
- 📰 Defining Main Functions in Python
- 🎬 Defining Main Functions in Python
You can visit the following resources to lean more about testing in Python:
Mike Lesselyoung on Sept. 3, 2023
Sorry, but why you pronounce the “s” in re”s”ources as if it were a “z”? It is not a z, it is an s.