After sharing about<span>Pydantic</span>, I’m back to learning<span>Python</span> with a focus on<span>__name__</span> and <span>__main__</span>. Why discuss this? Isn’t it just a line of code written below the executed file?
1
if if __name__ == '__main__'
Have you ever been confused about why the code block below this line in the called file does not execute? But it can execute when running the file? I’m not joking; I was really confused about this until I read this article I wrote.
<span>__name__</span> – What is it for?
The official explanation
<span>__name__</span> is a built-in variable in Python, and every module has this attribute. It acts like an “ID card” for the module, telling us what identity the current module is running under.
- • When the module runs independently:
<span>__name__</span>‘s value is<span>__main__</span> - • When the module is imported:
<span>__name__</span>‘s value is the module’s filename (without the .py extension)
After reading the definition, the mystery is solved. In simple terms, the <span>__name__</span> attribute of the file object is assigned different values in different situations: either <span>__main__</span> or the module’s filename.
Its usage
The most common usage is to add a conditional check at the end of the file:
1
2
3
4
5
def main():
print("This is the main program logic")
if __name__ == "__main__":
main() # This will only execute when this file is run directly
This structure allows the code to be both importable and executable independently.
How to use it effectively?
Common usage scenarios
This pattern is particularly useful in the following scenarios:
- • Utility modules: Provide functions for other modules to call while also being able to run specific tasks directly
- • Testing code: Add test cases at the bottom of the module for easy debugging
- • Library development: Ensure that library functions do not execute unexpectedly when imported
Final thoughts
<span>__name__</span> and <span>__main__</span>: Remember its function simply and clearly. When you write a bunch of code in a file and want some of it not to execute when the file is imported, just place that code block inside <span>if __name__ == '__main__'</span>. The startup file and the main function are generally also written in <span>if __name__ == '__main__'</span>, such as in the <span>manage.py</span> of a Django project.
Isn’t that simple? As for why the code of the imported file executes, that will be explained next time.
Recommended Reading:
Python urllib module – Another library for handling network requests
Python Type Annotations: From Guessing Games to Clear Programming
✨Follow me, to get more Python learning resources, practical projects, and industry updates! Reply “python learning” in the public account backend to get Python learning e-books!