ZetCode

Python package

last modified November 17, 2026 Python 3.15

In this article we show how to organize Python code in packages.

A package is a directory of modules that are imported under a common name. A module is a single Python file; a package groups related modules, and it can contain other packages, called subpackages. The dotted name shop.models.product refers to the product module in the models subpackage of the shop package.

When a project grows to dozens or hundreds of modules, packages are essential. Database code can live in one package, user interface code in another, and each package has its own namespace, so modules with the same name in different packages do not clash.

Python has two kinds of packages. A regular package is a directory with an __init__.py file. A namespace package, added in Python 3.3, has no __init__.py file and can be spread over several directories. Regular packages are the usual choice; the missing __init__.py is not a shortcut, but a different kind of package.

The word package also has a second meaning: a distribution package is something we install with pip, such as arrow or python-dateutil. A distribution package usually installs one import package of the same name, but not always, as we show at the end of the article. All examples are run from the directory that contains the package directories.

A simple package

The mymath directory contains an empty __init__.py file, which makes it a regular package, and the mfuns.py module.

mymath/mfuns.py
def square(x):
    return x * x


def cube(x):
    return x * x * x

The mfuns module defines two functions. Its full name is mymath.mfuns; the package name and the module name are separated with a dot.

import_forms.py
import mymath.mfuns
from mymath import mfuns
from mymath.mfuns import cube

print(mymath.mfuns.square(3))
print(mfuns.square(4))
print(cube(5))

The program shows three ways to import code from a package. The import mymath.mfuns statement binds the name mymath, so we must use the full dotted path. The from mymath import mfuns statement binds the module itself, and from mymath.mfuns import cube binds a single function. The tree command shows the layout of the package.

$ tree mymath
mymath
├── __init__.py
└── mfuns.py

0 directories, 2 files
$ python import_forms.py
9
16
125

A package is a module

When a package is imported, Python creates a module object for it. The module is initialized from the __init__.py file. What distinguishes a package from a plain module is the __path__ attribute: a list of directories that are searched for its submodules.

package_attrs.py
import mymath
import mymath.mfuns

print(type(mymath))
print(mymath.__name__)
print(mymath.__file__)
print(mymath.__path__)
print()
print(mymath.mfuns.__name__)
print(mymath.mfuns.__package__)
print(hasattr(mymath.mfuns, '__path__'))

The __file__ attribute of a regular package points to its __init__.py file. A submodule's __package__ attribute holds the name of the package it belongs to; Python uses it to resolve relative imports. The mfuns module has no __path__, so it cannot contain submodules.

$ python package_attrs.py
<class 'module'>
mymath
/home/user/python/mymath/__init__.py
['/home/user/python/mymath']

mymath.mfuns
mymath
False

Submodules are not imported automatically

Importing a package runs only its __init__.py file. The submodules are not loaded until we import them.

submodules.py
import mymath

try:
    print(mymath.mfuns.cube(2))
except AttributeError as e:
    print(f'error: {e}')

import mymath.mfuns

print(mymath.mfuns.cube(2))

After import mymath, the mymath.mfuns attribute does not exist, because the empty __init__.py does not import the submodule. The import mymath.mfuns statement loads the submodule and stores it as an attribute of the package. Large packages such as xml or email work the same way; we import the parts we need, for instance import xml.etree.ElementTree.

$ python submodules.py
error: module 'mymath' has no attribute 'mfuns'
8

__init__.py as the public interface

The __init__.py file can import names from the submodules. The users of the package then import everything from the package itself and do not need to know how the code is split into modules. See Python __init__.py file for more about this file.

geometry/shapes.py
import math
from dataclasses import dataclass


@dataclass
class Circle:
    radius: float

    def area(self):
        return math.pi * self.radius ** 2


@dataclass
class Rectangle:
    width: float
    height: float

    def area(self):
        return self.width * self.height

The shapes module defines two data classes.

geometry/measure.py
def total_area(shapes):
    return sum(shape.area() for shape in shapes)

The measure module computes the total area of a sequence of shapes.

geometry/__init__.py
from .shapes import Circle, Rectangle
from .measure import total_area

__version__ = '1.2.0'

The __init__.py file lifts the classes and the function to the package level with relative imports; the leading dot means the current package. It also defines the __version__ attribute, a common convention for package versions.

use_geometry.py
import geometry

shapes = [geometry.Circle(1.5), geometry.Rectangle(2, 3), geometry.Circle(0.5)]

for shape in shapes:
    print(f'{shape} area: {shape.area():.2f}')

print(f'total area: {geometry.total_area(shapes):.2f}')
print(f'geometry version: {geometry.__version__}')

The program uses geometry.Circle and geometry.total_area without mentioning the modules where they are defined. The internal layout can later change without breaking the users of the package.

$ python use_geometry.py
Circle(radius=1.5) area: 7.07
Rectangle(width=2, height=3) area: 6.00
Circle(radius=0.5) area: 0.79
total area: 13.85
geometry version: 1.2.0

Package initialization

The code in __init__.py runs once, when the package is first imported. Importing a submodule imports its parent package first.

config/__init__.py
print(f'running {__name__}/__init__.py')

settings = {'debug': False, 'db_name': 'test.db'}

The __init__.py file prints a message and defines a settings dictionary.

config/db.py
from . import settings

print(f'running {__name__}')

def connection_string():
    return f"sqlite:///{settings['db_name']}"

The db module imports the settings dictionary from its parent package with from . import settings.

init_order.py
import sys

print('importing config.db')
import config.db

print('importing config')
import config
from config import settings

print(config.db.connection_string())
print(settings)
print(sorted(name for name in sys.modules if name.startswith('config')))

The program imports the submodule first and the package second. The sys.modules dictionary caches every imported module under its full name.

The output shows that import config.db runs the package's __init__.py before the submodule. The later import config and from config import settings statements find the package in sys.modules, so no code runs a second time. Keep __init__.py light: every import of any submodule pays for its work.

$ python init_order.py
importing config.db
running config/__init__.py
running config.db
importing config
sqlite:///test.db
{'debug': False, 'db_name': 'test.db'}
['config', 'config.db']

Subpackages

A package can contain other packages. The shop package has two subpackages, models and services; each one has its own __init__.py file.

shop/models/product.py
from dataclasses import dataclass


@dataclass
class Product:
    name: str
    price: float

The product module defines the Product class.

shop/models/__init__.py
from .product import Product

The models package re-exports the class, so other code can write from shop.models import Product.

shop/services/discounts.py
DISCOUNTS = {'regular': 0.0, 'member': 0.05, 'vip': 0.15}


def discount_for(customer_type):
    return DISCOUNTS.get(customer_type, 0.0)

The discounts module maps customer types to discount rates.

shop/services/pricing.py
from ..models import Product
from .discounts import discount_for


def final_price(product, customer_type):
    rate = discount_for(customer_type)
    return round(product.price * (1 - rate), 2)


if __name__ == '__main__':
    p = Product('keyboard', 80.0)
    print(f'{p.name}: {final_price(p, "regular")} / {final_price(p, "vip")}')

The pricing module uses relative imports to reach code in its own package and in a sibling package. The single dot in .discounts refers to shop.services; the two dots in ..models go one level up to shop and then down to shop.models. The __main__ block is used in the next section.

use_shop.py
from shop.models import Product
from shop.services.pricing import final_price

products = [Product('mouse', 25.0), Product('monitor', 220.0)]

for p in products:
    for customer in ('regular', 'member', 'vip'):
        print(f'{p.name:8} {customer:8} {final_price(p, customer):7.2f}')

The program imports from both subpackages with absolute imports. The shop/__init__.py and shop/services/__init__.py files are empty.

$ tree shop
shop
├── __init__.py
├── models
│   ├── __init__.py
│   └── product.py
└── services
    ├── __init__.py
    ├── discounts.py
    └── pricing.py

2 directories, 6 files
$ python use_shop.py
mouse    regular    25.00
mouse    member     23.75
mouse    vip        21.25
monitor  regular   220.00
monitor  member    209.00
monitor  vip       187.00

Running a module inside a package

Relative imports are resolved against the module's __package__ attribute. When a file is run directly by its path, it becomes the __main__ module with no parent package, and its relative imports fail.

The first command runs the pricing.py file by its path and gets an ImportError. The second command uses the -m option with the module's dotted name. Python imports the parent packages first, sets __package__ to shop.services, and runs the module as __main__, so the relative imports work. See Python relative imports for more details.

$ python shop/services/pricing.py
Traceback (most recent call last):
  File "/home/user/python/shop/services/pricing.py", line 1, in <module>
    from ..models import Product
ImportError: attempted relative import with no known parent package
$ python -m shop.services.pricing
keyboard: 80.0 / 68.0

__all__ and star imports

The from package import * statement imports the names listed in the package's __all__ variable. If __all__ lists submodule names, the submodules are imported too. Without __all__, the star import takes the public names defined in __init__.py (those not starting with an underscore) and loads no submodules.

textutils/__init__.py
__all__ = ['cases', 'counting', 'VERSION']

VERSION = '0.3'
_cache = {}

The package exports two submodules and the VERSION constant. The internal submodule and the _cache variable are not part of the public interface.

textutils/cases.py
def snake_case(text):
    return '_'.join(text.lower().split())

The cases module converts text to snake case.

textutils/counting.py
def word_count(text):
    return len(text.split())

The counting module counts words.

star_import.py
from textutils import *

text = 'Old pond frog jumps in'

print(cases.snake_case(text))
print(counting.word_count(text))
print(VERSION)

for name in ('internal', '_cache'):
    print(f'{name} imported: {name in globals()}')

After the star import, the cases and counting modules and the VERSION constant are available in the program's namespace. The internal module was never imported, and _cache was not copied. Star imports make it hard to tell where a name comes from, so they are best kept for the interactive interpreter.

$ python star_import.py
old_pond_frog_jumps_in
5
0.3
internal imported: False
_cache imported: False

Executable packages with __main__.py

A package with a __main__.py file can be run with python -m package. This is how tools such as python -m venv, python -m pip, and python -m http.server work.

greeter/core.py
def greet(name):
    return f'Hello, {name}!'

The core module contains the logic of the package.

greeter/__main__.py
import sys

from .core import greet

names = sys.argv[1:] or ['there']

for name in names:
    print(greet(name))

The __main__.py file is the entry point. It reads the names from the command line arguments and greets each of them. Since the package is run with -m, the relative import works.

$ python -m greeter
Hello, there!
$ python -m greeter Lucia Peter
Hello, Lucia!
Hello, Peter!

Namespace packages

A directory without an __init__.py file can still be imported. Python collects all directories with the package name found on sys.path and merges them into one namespace package. This lets separately installed distributions add modules to a shared package, for instance plugins. See Python namespace packages for more details.

ns1/plugins/csv_export.py
def export(rows):
    return '\n'.join(','.join(map(str, row)) for row in rows)

The ns1/plugins directory contains a CSV exporter.

ns2/plugins/md_export.py
def export(rows):
    return '\n'.join('| ' + ' | '.join(map(str, row)) + ' |' for row in rows)

The ns2/plugins directory contains a Markdown table exporter. Neither plugins directory has an __init__.py file.

namespace.py
import sys

sys.path[1:1] = ['ns1', 'ns2']

import plugins
from plugins import csv_export, md_export

print(plugins.__path__)
print(plugins.__file__)
print(csv_export.__file__)
print(md_export.__file__)

rows = [('pen', 3), ('book', 12)]
print(csv_export.export(rows))
print(md_export.export(rows))

We put the ns1 and ns2 directories on the module search path, right after the script's directory. The plugins package's __path__ then contains both directories; in Python 3.15 its type is NamespacePath (older versions show _NamespacePath). A namespace package has no __init__.py file, so its __file__ is None.

$ python namespace.py
NamespacePath(['/home/user/python/ns1/plugins', '/home/user/python/ns2/plugins'])
None
/home/user/python/ns1/plugins/csv_export.py
/home/user/python/ns2/plugins/md_export.py
pen,3
book,12
| pen | 3 |
| book | 12 |

Package data files

Packages can ship data files, such as templates, configuration, or text resources. The importlib.resources module reads them relative to the package, wherever the package is installed; it also works for packages loaded from zip files, where there is no real directory.

quotes/data/quotes.txt
Simple is better than complex.
Readability counts.
Errors should never pass silently.

The quotes package has an empty __init__.py file and a data subdirectory with this text file.

resources_read.py
from importlib.resources import files

data = files('quotes') / 'data' / 'quotes.txt'

print(data.name)
print(data.is_file())

for n, line in enumerate(data.read_text(encoding='utf-8').splitlines(), 1):
    print(n, line)

The files function returns a Traversable object for the package. We navigate to the data file with the / operator and read it with read_text. Unlike paths built from __file__, this does not depend on how the package was installed.

$ python resources_read.py
quotes.txt
True
1 Simple is better than complex.
2 Readability counts.
3 Errors should never pass silently.

Lazy imports in __init__.py

Re-exporting names in __init__.py has a cost: importing the package loads every submodule, even those the program never uses. Python 3.15 adds lazy imports (PEP 810). A lazy import or lazy from ... import statement binds the name immediately, but the module is loaded only when the name is first used.

reports/pdf.py
print(f'loading {__name__}')


def export_pdf(title):
    return f'{title}.pdf written'

The pdf module prints a message when it is loaded.

reports/charts.py
print(f'loading {__name__}')


def bar_chart(values):
    return '\n'.join('#' * v for v in values)

The charts module also announces its loading.

reports/__init__.py
lazy from .pdf import export_pdf
lazy from .charts import bar_chart

__all__ = ['export_pdf', 'bar_chart']

The package's __init__.py re-exports one function from each submodule with lazy from imports.

lazy_package.py
import sys

import reports

loaded = sorted(name for name in sys.modules if name.startswith('reports'))
print(f'after import: {loaded}')

print(reports.export_pdf('sales'))

loaded = sorted(name for name in sys.modules if name.startswith('reports'))
print(f'after export_pdf: {loaded}')

After import reports, only the package itself is in sys.modules. The first access to reports.export_pdf loads the reports.pdf submodule; the charts submodule is never loaded. The lazy soft keyword is a syntax error in Python 3.14 and older, where the same effect requires a module-level __getattr__ function (PEP 562).

$ python lazy_package.py
after import: ['reports']
loading reports.pdf
sales.pdf written
after export_pdf: ['reports', 'reports.pdf']

Installed packages

Third-party packages are installed with pip into the site-packages directory of a Python environment. It is good practice to install them into a virtual environment rather than into the system Python; see Python venv.

dist_info.py
import importlib.metadata as metadata
import sysconfig
from pathlib import Path

import arrow

site = Path(sysconfig.get_path('purelib'))
print(site)
print(Path(arrow.__file__).relative_to(site))
print(f"arrow {metadata.version('arrow')}")

for req in metadata.requires('arrow'):
    if 'extra ==' not in req:
        print(f'  requires {req}')

dists = metadata.packages_distributions()

for name in ('arrow', 'dateutil', 'tzdata'):
    print(f'import {name:9} -> distribution {dists[name][0]}')

The program prints the site-packages directory of the running environment and the location of the arrow package inside it. The importlib.metadata module reads the metadata of installed distributions: the version and the requirements of arrow. The packages_distributions function maps import names to distribution names; the dateutil import package comes from the python-dateutil distribution.

We create a virtual environment in the .venv directory, install arrow into it with pip, and run the program with the environment's interpreter. The output also shows that arrow is a regular package: a directory with an __init__.py file.

$ python -m venv .venv
$ .venv/bin/python -m pip install -q arrow
$ .venv/bin/python dist_info.py
/home/user/python/.venv/lib/python3.15/site-packages
arrow/__init__.py
arrow 1.4.0
  requires python-dateutil>=2.7.0
  requires backports.zoneinfo==0.2.1;python_version<'3.9'
  requires tzdata;python_version>='3.9'
import arrow     -> distribution arrow
import dateutil  -> distribution python-dateutil
import tzdata    -> distribution tzdata

Source

Packages – The Python Tutorial

Packages – Python language reference

importlib.resources – Package resource reading

PEP 420 – Implicit namespace packages

PEP 810 – Explicit lazy imports

In this article we have organized Python code in packages. See also Python module, Python __init__.py file, Python relative imports, and Python namespace packages.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.