How you name and split modules decides whether a Python project is still easy to change a year later. These best practices for Python modules and packages are not rigid rules. They are patterns that make code easier to read, test and refactor, whether you are writing a script that may grow into a tool or a library other people install.
Every practice below is shown on one small package called shopkit, which prices an order. All the code was run on Python 3.14, and the output shown is what it printed.
shopkit/
├── pyproject.toml
├── src/
│ └── shopkit/
│ ├── __init__.py
│ ├── _parsing.py
│ ├── cli.py
│ ├── orders.py
│ └── pricing.py
└── tests/
└── test_shopkit.pyIf you have not set up a project like this before, Organize Python Projects explains the src layout and pyproject.toml.
Naming conventions that communicate intent
Module names use lowercase letters with underscores between words, as PEP 8 asks. A module called data_processor.py says what it holds. A module called dp.py or utils2.py saves a few keystrokes and makes every reader open the file to find out what is inside.
Name a module after its role, not its implementation. json_storage.py describes how the data is saved, and that may become SQLite next month. persistence.py describes what the module is for, so the name survives the change.
Never give a module the name of a standard library module. Here is a two-line script saved as random.py:
import random
print(random.randint(1, 6))Running it fails, because import random finds your own file first:
AttributeError: module 'random' has no attribute 'randint' (consider renaming
'/home/you/random.py' since it has the same name as the standard library module
named 'random' and prevents importing that standard library module)Python 3.13 and later print that hint. Older versions stop at the first half of the message, which is much harder to diagnose. Renaming the file to dice.py fixes it.
Package names follow the same rules and also define a namespace. A good package name is unlikely to collide with another installed package, tells the reader what the package provides, and is short enough to type in an import.
Keeping modules focused and cohesive
A well-designed module does one thing that you can describe in one sentence. If you need the word "and" to describe it, it is probably two modules. shopkit/pricing.py only calculates prices:
"""Price calculations for an order."""
from decimal import Decimal
TAX_RATE = Decimal("0.08")
def subtotal(lines):
"""Add up quantity times unit price over (quantity, unit_price) pairs."""
return sum((qty * price for qty, price in lines), Decimal(0))
def total(lines, tax_rate=TAX_RATE):
"""Return the subtotal plus tax, rounded to cents."""
amount = subtotal(lines) * (1 + tax_rate)
return amount.quantize(Decimal("0.01"))Reading order text is a different job, so it lives in its own module, shopkit/_parsing.py:
"""Internal helpers. Not part of the public API."""
from decimal import Decimal
def parse_line(text):
"""Turn '3 x 4.50' into (3, Decimal('4.50'))."""
qty, _, price = text.partition(" x ")
return int(qty), Decimal(price)shopkit/orders.py joins the two:
"""Turn the text of an order into a total."""
from shopkit._parsing import parse_line
from shopkit.pricing import total
def order_total(text):
"""Total for an order written as one 'quantity x price' per line."""
lines = [parse_line(row) for row in text.splitlines() if row.strip()]
return total(lines)When a module grows past about five hundred lines, look for groups of functions that are called together and change together. Those groups are candidates for their own modules. The opposite problem also exists: several tiny modules that are always imported together and always change together are easier to read as one file.
Designing clean package APIs
A package's public API is everything a user of the package is expected to import. Everything else is an implementation detail that you can change freely. The __init__.py file draws that line. This is shopkit/__init__.py:
"""shopkit: small helpers for pricing an order."""
from shopkit.orders import order_total
from shopkit.pricing import subtotal, total
__all__ = ["order_total", "subtotal", "total"]Users now write from shopkit import order_total and never need to know which file the function lives in, so you can move it later without breaking them. __all__ lists the public names and controls what a wildcard import brings in:
from shopkit import *
print(sorted(name for name in dir() if not name.startswith("_")))['order_total', 'subtotal', 'total']parse_line is not in that list. Its module name starts with an underscore, which tells readers and tools that it is private. Python does not enforce this, but code that imports shopkit._parsing directly accepts that it may break in the next release.
Adding a public name is safe. Removing or renaming one needs a deprecation period in which the old name still works and warns. Suppose total() used to be called grand_total(). Keep the old name in pricing.py for a release, and add it to __init__.py and __all__ for as long as it exists:
import warnings
def grand_total(lines, tax_rate=TAX_RATE):
"""Old name of total(). Kept for one release."""
warnings.warn(
"grand_total() is deprecated; use total()",
DeprecationWarning,
stacklevel=2,
)
return total(lines, tax_rate)A script that still calls the old name keeps working and is told what to change:
from decimal import Decimal
from shopkit import grand_total
print(grand_total([(2, Decimal("9.99"))]))demo.py:5: DeprecationWarning: grand_total() is deprecated; use total()
print(grand_total([(2, Decimal("9.99"))]))
21.58stacklevel=2 makes the warning point at the caller's line (demo.py:5) instead of the line inside pricing.py, which is the line the user has to edit.
Structuring imports for readability
Use absolute imports by default. They say exactly where each module lives and read the same from any file in the project. Relative imports are fine inside a package, but they fail in a file that is run directly. If cli.py contained from .orders import order_total, this is what happens:
python src/shopkit/cli.py "3 x 1.25"ImportError: attempted relative import with no known parent packageRunning the same file as a module of the installed package works, with either style of import:
python -m shopkit.cli "3 x 1.25"4.05Group imports in three blocks separated by blank lines: standard library, third-party, then your own package. Sort each block alphabetically:
import json
import sys
from decimal import Decimal
from pathlib import Path
import requests
from shopkit.orders import order_total
from shopkit.pricing import subtotalYou do not have to sort by hand. ruff check --select I (or isort) checks the order, and ruff check --select I --fix rewrites it. The block above passes that check as written.
Avoid wildcard imports in application code. They put an unknown set of names into the module, so a reader cannot tell where a name came from. They are acceptable in an interactive session, or inside an __init__.py that deliberately republishes a submodule that defines __all__.
Project structure that scales
Keep only project-wide files in the project root: pyproject.toml, the README and the license. All importable code goes inside the named package, as in the tree at the top of this article.
Put code that should run only as a program behind a __name__ guard, so importing the module has no side effects. This is shopkit/cli.py:
"""Command line entry point."""
import sys
from shopkit.orders import order_total
def main(argv=None):
args = sys.argv[1:] if argv is None else argv
print(order_total("\n".join(args)))
if __name__ == "__main__":
main()python -m shopkit.cli "2 x 9.99" "1 x 4.50"26.44Make dependencies flow in one direction. In shopkit, cli imports orders, orders imports pricing and _parsing, and those two import nothing from the package. No module imports from a module above it. That keeps the dependency graph a tree: you can read, test and change pricing.py without opening anything else, and a circular import cannot happen.
Test through the public API, the way a user would import it. This is tests/test_shopkit.py:
from decimal import Decimal
from shopkit import order_total, subtotal
def test_subtotal_adds_quantity_times_price():
assert subtotal([(2, Decimal("9.99")), (1, Decimal("4.50"))]) == Decimal("24.48")
def test_order_total_adds_tax_and_rounds_to_cents():
assert order_total("2 x 9.99\n1 x 4.50") == Decimal("26.44")After pip install -e . in a virtual environment, pytest -q reports:
2 passed in 0.00sBecause the tests import only from shopkit, you can later split pricing.py or move order_total to another module, and the tests keep passing as long as __init__.py still exports the same names. That is the whole point of a deliberate public API.
Rune AI
Key Insights
- Name modules with lowercase letters and underscores; avoid names that shadow standard library modules.
- Each module should serve one clear purpose; split when it exceeds 500 lines or mixes unrelated concerns.
- Use init.py to curate the public API by re-exporting key names and defining all.
- Prefer absolute imports for clarity; use relative imports only within large, deeply nested packages.
- Structure your project so that dependencies flow in one direction from high-level orchestrators to low-level utilities.
Frequently Asked Questions
Should every Python file I write be a module?
How should I handle versioning for my packages?
When should I use a class instead of a module with functions?
Conclusion
The best practices for Python modules and packages are not arbitrary rules. They are patterns that have emerged from decades of collective experience about what keeps codebases readable, testable, and maintainable as they grow. Name modules clearly, keep them focused, design clean package APIs through init files, use absolute imports by default, and structure your project so that a new developer can find code by thinking about the problem domain.
More in this topic
Organize Python Projects
Learn how to structure a Python project from a single script to a maintainable package with clear directory layout, configuration, and dependency management.
Create Hashes with Python `hashlib`
Learn how to use Python's hashlib module to create cryptographic hashes for data integrity verification, file checksums, and secure password storage.
Install Python on Your Computer
Install Python on Windows, macOS, or Linux, check the version, and understand which command to use next.