Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 52 of 70

Python packages and how to lay out a project

Group Python modules into packages with folders and __init__.py, use absolute and relative imports, and organise a small project, with a tested layout.

14 minModules and packagesUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonBuild a small package of several modules, import from it with absolute and relative imports, and lay out a sensible project folder.

After this lesson you can organise a program into a package of modules, import between them correctly, and avoid the most common import error.

From module to package

A module is one file. Once a project has a handful of related files, you group them in a folder. A folder of modules, marked by a file named __init__.py, is a package. You use it with dotted names: shop.pricing means "the module pricing inside the package shop".

Let us build a small one for the shop. The folder will be called shop and sit next to a main script. Here are the files.

python
#file: shop/__init__.py
"""A tiny package for shop calculations."""
python
#file: shop/pricing.py
TAX_RATE = 0.18

def add_tax(amount):
    return round(amount * (1 + TAX_RATE), 2)
python
#file: shop/inventory.py
from .pricing import add_tax

STOCK = {"tea": 40, "milk": 12}

def stock_value(prices):
    total = sum(prices[name] * count for name, count in STOCK.items())
    return add_tax(total)
python
#file: shop/reports/__init__.py
python
#file: shop/reports/daily.py
from ..inventory import STOCK
from shop.pricing import add_tax

def summary():
    return f"{len(STOCK)} products in stock, tax on 100 is {add_tax(100)}"
python
#file: main.py
from shop import inventory
from shop.reports import daily

print(inventory.stock_value({"tea": 5, "milk": 3}))
print(daily.summary())

Here is the layout, listing only the Python files:

bash
find . -name "*.py" | sort
result
./main.py
./shop/__init__.py
./shop/inventory.py
./shop/pricing.py
./shop/reports/__init__.py
./shop/reports/daily.py

The role of init.py

The file __init__.py runs when the package is first imported. In the example the shop one holds only a docstring, and shop/reports/__init__.py is empty. An empty file is perfectly normal: its presence is what matters. Later you might use it to expose a friendlier interface, which you will see below. Modern Python can also import a folder without __init__.py (a "namespace package"), but those behave differently, so for your own projects, add the file.

Importing from a package

Absolute imports spell out the full path from the top of the project:

python
import shop
from shop.pricing import add_tax
from shop import inventory

print(shop.__doc__)
print(add_tax(200))
print(inventory.STOCK)
result
A tiny package for shop calculations.
236.0
{'tea': 40, 'milk': 12}

A submodule is not available just because you imported the package. import shop does not load shop.pricing by itself unless the package's __init__.py imports it, so import the submodule you need.

Relative imports

Inside a package, modules can refer to each other with dots. One dot means "this package" and two dots mean "the package above". In inventory.py above, from .pricing import add_tax loads the neighbouring module. In reports/daily.py, from ..inventory import STOCK goes up one level first. Relative imports keep working if you rename the top-level package. Absolute imports, as used for shop.pricing in the same file, are often easier to read. Pick one style and stay consistent.

Now run the main script from the project folder:

bash
python3 main.py
result
278.48
2 products in stock, tax on 100 is 118.0

The relative import trap

Relative imports only work when the file is loaded as part of its package. If you run a file inside the package directly, Python treats it as a loose script with no parent, and the dots have nothing to refer to:

bash
python3 shop/reports/daily.py 2>&1 | tail -1
result
ImportError: attempted relative import with no known parent package

The fix is to run something outside the package that imports it, as main.py does. Use python3 -m shop.reports.daily if you need to run a module inside a package directly.

A friendlier package interface

Users should not need to know which file holds each function. You can re-export names in __init__.py:

python
#file: tidy/__init__.py
from .helpers import clean

__all__ = ["clean"]
python
#file: tidy/helpers.py
def clean(text):
    return " ".join(text.split())
python
from tidy import clean

print(clean("  too    many   spaces  "))
result
too many spaces

The list __all__ says which names are public when someone writes from tidy import *. It is also a helpful note for readers.

A sensible project layout

A small project can follow a simple shape:

text
shop-report/
    main.py              the script you run
    requirements.txt     packages to install
    shop/                your package
        __init__.py
        pricing.py
        inventory.py
    tests/               test files (see the testing lesson)
    .gitignore           lists .venv and other generated files

Keep one entry point at the top, put reusable code in the package, and keep tests beside, not inside, it. Avoid very deep nesting. Two or three levels are enough for most programs. Avoid circular imports too, where module A imports B and B imports A, by moving shared code into a third module.

Where the code should go

A reasonable question is when to turn a module into a package. A simple guide is to wait until a file passes a few hundred lines, or contains two or three clearly separate topics, and then split it by topic. In the shop example, price calculations live in one module and stock handling in another, so each file has one theme and a name that tells you what is inside.

You can also see a package's contents from Python itself. The __name__ attribute shows how a package or module is known to Python:

python
import shop

print(shop.__name__)
print(shop.inventory.__name__)
result
shop
shop.inventory

Notice that shop.inventory is available here because an earlier example already imported that submodule. Python keeps loaded submodules as attributes of the package.

Common mistakes

  • Running a package file directly when it uses relative imports.
  • Forgetting __init__.py and then wondering why imports behave oddly.
  • Circular imports. Move the shared part into a third module.
  • Naming a package after a standard module, such as random or test.
  • Starting Python from the wrong folder, so the package is not on the search path.
  • Importing a submodule that was never loaded and getting an AttributeError.

Exercise

Make a package called greeter with a module hello.py containing say(name) that returns "Hello, <name>". In __init__.py, re-export say. Then import it with from greeter import say.

Show one possible answer
python
#file: greeter/__init__.py
from .hello import say
python
#file: greeter/hello.py
def say(name):
    return f"Hello, {name}"
python
from greeter import say

print(say("Asha"))
result
Hello, Asha

Key points

  • A package is a folder of modules. A file named __init__.py marks the folder as a package and runs when the package is imported.
  • Import from a package with dotted names, such as from shop.pricing import add_tax.
  • Inside a package, relative imports such as from .pricing import add_tax refer to sibling modules.
  • A file that uses relative imports must be run as part of the package, not directly.
  • Keep a simple layout: a top-level script, your package folder, and tests next to it.

Check yourself

1. What turns a folder of .py files into a regular package?
2. What does from . import pricing mean inside the shop package?
3. Why does running python3 shop/reports/daily.py fail if that file uses a relative import?
4. What does __init__.py often contain in a small project?