Skip to content

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.


Let’s create a utility module for a hypothetical mathematical library.

geometry.py
import math
# A constant
PI = math.pi
# Functions
def area_of_circle(radius):
return PI * (radius ** 2)
def circumference(radius):
return 2 * PI * radius

You can now use this in another file:

app.py
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.

  • If you run python geometry.py, Python sets __name__ to "__main__".
  • If you import geometry, Python sets __name__ to "geometry".
geometry.py (Updated)
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!")

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.

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().


When you say import my_lib, Python looks in a specific list of directories. If it can’t find it, it raises ModuleNotFoundError.

  1. The Input Script Directory: The folder where the script you are running is located.
  2. Standard Library: Built-in modules like os and sys.
  3. Site-Packages: Third-party libraries installed via pip.
check_path.py
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)

RuleReason
Use Snake Casemy_module.py is standard; MyModule.py is not.
Avoid Library NamesNaming your file math.py or random.py will break imports.
Use DocstringsAdd a triple-quoted string at the very top of the module.
Keep Logic in FunctionsAvoid “Global” code that runs immediately upon import.