Creating Custom Modules
A Module in Python is simply a file ending in .py. While every script you write is technically a module, professional development involves splitting your logic into many modules to keep code clean, testable, and reusable.
When you import a file, you aren’t just linking to it—you are executing it to create a new Namespace.
1. Module Basics
Section titled “1. Module Basics”Let’s create a utility module for a hypothetical mathematical library.
import math
# A constantPI = math.pi
# Functionsdef area_of_circle(radius): return PI * (radius ** 2)
def circumference(radius): return 2 * PI * radiusYou can now use this in another file:
import geometry
print(geometry.area_of_circle(5))2. The Entry Point: if __name__ == "__main__"
Section titled “2. The Entry Point: if __name__ == "__main__"”When you import geometry, Python executes every line of geometry.py. If you had a print("Starting...") at the top level of geometry.py, it would run as soon as you imported it.
To prevent code (like tests or scripts) from running during an import, we use the __name__ check.
How it Works:
Section titled “How it Works:”- If you run
python geometry.py, Python sets__name__to"__main__". - If you
import geometry, Python sets__name__to"geometry".
def area_of_circle(radius): return 3.14 * (radius ** 2)
if __name__ == "__main__": # This block ONLY runs if you execute this file directly. # Excellent for unit tests or manual verification. print("Testing geometry module...") assert area_of_circle(1) == 3.14 print("Test passed!")3. Under the Hood: The Module Namespace
Section titled “3. Under the Hood: The Module Namespace”When you import a module, Python creates a Module Object. This object has its own __dict__ attribute, which stores all the functions, classes, and variables defined in the file.
Name Conflicts
Section titled “Name Conflicts”Because each module has its own namespace, you can have a function named calculate() in module_a.py and another named calculate() in module_b.py without them ever clashing. You access them as module_a.calculate() and module_b.calculate().
4. Searching for Modules: sys.path
Section titled “4. Searching for Modules: sys.path”When you say import my_lib, Python looks in a specific list of directories. If it can’t find it, it raises ModuleNotFoundError.
The Order of Search
Section titled “The Order of Search”- The Input Script Directory: The folder where the script you are running is located.
- Standard Library: Built-in modules like
osandsys. - Site-Packages: Third-party libraries installed via
pip.
import sys# sys.path is just a list of strings.# You can actually append to it at runtime to import from# unusual locations, though this is rarely recommended.print(sys.path)5. Summary Table: Module Best Practices
Section titled “5. Summary Table: Module Best Practices”| Rule | Reason |
|---|---|
| Use Snake Case | my_module.py is standard; MyModule.py is not. |
| Avoid Library Names | Naming your file math.py or random.py will break imports. |
| Use Docstrings | Add a triple-quoted string at the very top of the module. |
| Keep Logic in Functions | Avoid “Global” code that runs immediately upon import. |