Deep Understanding of __main__ and __name__ in Python
This article explains the special built‑in identifiers __main__ and __name__ in Python, describing how they indicate a module's execution context, how to use them to separate script and library code, and provides multiple practical code examples.
In Python, __main__ is a special built‑in name that refers to the entry point of the currently executing module. When a script is run directly, the interpreter treats the file as the "main module" and sets its __name__ attribute to "__main__".
Basic concepts
Each Python file is a module; when executed from the command line, it becomes the main module with __name__ == "__main__" . Placing code under an if __name__ == "__main__": block ensures that it runs only when the module is executed directly, not when imported.
Example
def greet(name):
print(f"Hello, {name}!")
if __name__ == "__main__":
greet("World")Running python example.py prints "Hello, World!" because the file is the main module. Importing example elsewhere does not execute the greeting because __name__ will be "example".
Uses
Dual role of scripts and modules: a file can be both importable and executable.
Unit testing: test code placed under the if __name__ == "__main__": block runs only when the module is executed directly.
Initialization or configuration: setup code (e.g., database connections, logging) can be guarded to avoid side effects on import.
Deep dive into __name__
Every module has a built‑in __name__ attribute. When run as a script, its value is "__main__"; when imported, it is the module's filename without the .py extension. This enables developers to write code that works both as a library and as a standalone program.
Application scenarios
1. Running test code
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3)) # test add function2. Initialization or configuration
def setup_logging():
# configure logging system
pass
if __name__ == "__main__":
setup_logging()
# main program logic3. Command‑line scripts
import argparse
def main(args):
print(f"Processing file: {args.filename}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="The file to process")
args = parser.parse_args()
main(args)4. GUI applications
import tkinter as tk
def create_window():
window = tk.Tk()
window.title("My Application")
window.mainloop()
if __name__ == "__main__":
create_window()Conclusion
The if __name__ == "__main__": pattern embodies Python's modular and flexible design principles, allowing developers to write reusable, maintainable code that can serve both as a library and as an executable script.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.