Creating Custom Modules
Any Python file is a module! Create your own modules to organize code into logical, reusable units.
15 min•By Priygop Team•Updated 2026
Custom Modules
Custom Modules
# Imagine we have a file called 'helpers.py':
# ---- helpers.py ----
# def greet(name):
# return f"Hello, {name}!"
#
# def add(a, b):
# return a + b
#
# PI = 3.14159
# ---- end helpers.py ----
# Then in main.py:
# from helpers import greet, add, PI
# print(greet("Alice"))
# print(add(5, 3))
# Demo: simulating a module
class MathHelper:
PI = 3.14159
E = 2.71828
@staticmethod
def circle_area(r):
return MathHelper.PI * r ** 2
@staticmethod
def factorial(n):
if n <= 1: return 1
return n * MathHelper.factorial(n - 1)
# Use it like a module
print(f"PI = {MathHelper.PI}")
print(f"Circle area (r=5): {MathHelper.circle_area(5):.2f}")
print(f"5! = {MathHelper.factorial(5)}")
# Module best practices
# 1. Keep modules focused (one purpose)
# 2. Use descriptive names (utils.py, database.py)
# 3. Add docstrings to explain the module
# 4. Keep imports at the top of the fileTip
Tip
Keep modules focused — one module per responsibility. utils.py, validators.py, models.py is cleaner than one huge helpers.py.
Diagram
Loading diagram…
Module = file, Package = folder + __init__.py, Library = pip.
Common Mistake
Warning
Naming your file the same as a standard library module (e.g., random.py, json.py) shadows the built-in. Use unique names.
Quick Quiz
Practice Task
Note
(1) Create a helpers.py module. (2) Import functions from it. (3) Add a docstring to your module.