Creating Your Own Modules
Once a program grows beyond a hundred or so lines, it becomes easier to manage if you split it across several files. Any Python file you write can be imported as a module, and folders of modules become packages.
Your first module
Create two files in the same folder. The first holds reusable tools; the second is the program you run.
# kes.py
VAT_RATE = 0.16
def format_kes(amount):
"""Return an amount as a Kenyan shilling string, e.g. KES 2,500.00."""
return f"KES {amount:,.2f}"
def add_vat(amount):
"""Return the amount including 16% VAT."""
return amount * (1 + VAT_RATE)
# main.py
import kes
price = 2500
print(kes.format_kes(price))
print(kes.format_kes(kes.add_vat(price)))
print("VAT rate:", kes.VAT_RATE)
Run python main.py:
The module name is the file name without .py. Everything defined at the top level of kes.py (functions, variables, classes) is available as kes.something. You can also write from kes import format_kes, exactly as with built-in modules (see Importing Modules).
The triple-quoted strings under each function are docstrings. Anyone can read them with help(kes.format_kes), and editors like VS Code show them when you hover over the function.
Running code only when a file is the main program
Importing a module runs all of its top-level code once. That's a problem if the module also contains test code or a demo. Python solves this with a special variable, __name__. It equals "__main__" when the file is run directly, and the module's own name when it's imported.
# greet.py
def greet(name):
return f"Habari, {name}!"
print("__name__ is", __name__)
if __name__ == "__main__":
# Only runs with: python greet.py
print(greet("Zawadi"))
Running python greet.py directly:
Now import it from another file:
# app.py
import greet
print(greet.greet("Otieno"))
The demo line inside the if block didn't run, because greet.py was imported rather than run. Putting your program's starting code inside if __name__ == "__main__": (often by calling a main() function) is a habit worth building from day one.
Packages: folders of modules
When you have several related modules, group them in a folder called a package. Add a file named __init__.py (it can be empty) to mark the folder as a regular package.
duka/
main.py
shop/
__init__.py
pricing.py
receipts.py
# shop/pricing.py
def apply_discount(price, percent):
return price - price * percent / 100
# shop/receipts.py
from .pricing import apply_discount # relative import: "pricing in this package"
def receipt_line(item, price, percent=0):
final = apply_discount(price, percent)
return f"{item}: KES {final:.2f}"
# main.py
from shop.receipts import receipt_line
from shop import pricing
print(receipt_line("Sugar", 200))
print(receipt_line("Rice", 1500, 10))
print(pricing.apply_discount(1000, 25))
Dots in an import path follow the folders: shop.receipts means "the receipts module inside the shop package". Inside a package, a leading dot (from .pricing import ...) is a relative import meaning "from this same package".
shop runs shop/__init__.py; a leading dot means "this same package".What goes in __init__.py?
Usually nothing. You can use it to make important names easier to reach. For example, adding from .receipts import receipt_line to shop/__init__.py lets other files write from shop import receipt_line.
How Python finds your modules
Python looks first in the folder of the script you run. That's why main.py can import kes.py or the shop package when they sit beside it. After the first import, Python saves a compiled copy in a __pycache__ folder to start faster next time. You can safely ignore or delete that folder, and it's normally left out of Git.
Running a module from the wrong folder. Relative imports such as from .pricing import ... only work when the file is imported as part of its package. Running python shop/receipts.py directly fails with "attempted relative import with no known parent package". Run the program from the top folder instead, with python main.py (or python -m shop.receipts).
Circular imports. If a.py imports b.py and b.py imports a.py, one of them will be only half-loaded when the other needs it, causing confusing ImportError or AttributeError messages. Move the shared code into a third module that both can import.
Tips for organising a project
- Group code by job:
storage.pyfor saving data,reports.pyfor printing summaries,main.pyto tie them together. - Use short, lowercase file names with underscores, and never reuse a standard library name such as
random.pyorjson.py. - Keep modules focused. If you can't describe a module in one sentence, it may need splitting.
- When a project needs third-party packages, record them in
requirements.txt(see pip & virtual environments).
Key points
- Any
.pyfile can be imported by its name (without.py). - Use
if __name__ == "__main__":for code that should run only when the file is executed directly. - A package is a folder of modules, marked with an
__init__.pyfile. - Use dotted paths (
shop.pricing) and relative imports (from .pricing import ...) inside packages. - Avoid circular imports and file names that clash with existing modules.
Tip: use the ← and → keys to move between pages.
