Clean Code Essentials: Imports, Modules, and the Magic of if __name__ == "__main__"
In the world of Python, clarity is everything. Instead of creating one giant, monolithic file, the best practice is to split your project into smaller, logical parts. This makes your code easier to maintain, test, and reuse across different projects.
Modules and Classes: Building with Blocks
Every .py file you create is a module. It can contain functions, variables, and—most importantly—classes. Importing allows us to use these tools wherever they are needed.
| import module: | Gives you access to everything inside the module. |
| from module import element: | This allows you to extract exactly what you need from a module — whether it is a class, function, instance, or a specific value (variable). This approach supports technical minimalism by avoiding namespace clutter and unnecessary memory usage when only a single tool is required. |
What is if __name__ == "__main__"?
This is one of Python’s most critical constructs. When you run a script, Python sets a special internal variable called __name__.
- If you run the file directly – __name__ is set to "__main__".
- If the file is imported by another script – __name__ takes the name of the file itself.
Why does this matter?
Without this check, any code written at the top level of your module would execute automatically the moment you import it. By using if __name__ == "__main__", we ensure that demonstration or testing code only runs when we explicitly launch that specific file.
Practical Example: System Monitor (MIT License)
This script demonstrates modularity in action. The SystemInfo class handles the logic, while the __main__ section serves as a practical demo.
# SAKS_Core_Example.py
# Author: Kajotte Studio | License: MIT
# Description: Demonstrating modularity and basic system data collection.
import platform
import os
class SystemInfo:
"""Class responsible for gathering environment information."""
def __init__(self):
self.os_name = platform.system()
self.node_name = platform.node()
self.release = platform.release()
def get_summary(self):
"""Returns a formatted system report."""
return f"System: {self.os_name} | Host: {self.node_name} | Release: {self.release}"
# Protection section to prevent execution on import
if __name__ == "__main__":
# This code executes ONLY when the file is run directly
print("--- Kajotte Studio: SystemInfo Module Demo ---")
monitor = SystemInfo()
print(monitor.get_summary())
print(f"Current Directory: {os.getcwd()}")
print("----------------------------------------------")
How to use it?
If you create a new file and writefrom SAKS_Core_Example import SystemInfo
you can use the class,
but the --- Demo ---
messages won't clutter your console.
It’s clean, modular, and follows the best industry standards!
👇
▒ Blog Guide: All Programming Posts in One Place. ▹ See