Skip to content

Module 14 · Python Modules and Packages — topic 7 of 13

Packages

Grouping modules into packages: package directories, dotted imports, subpackages, absolute and relative imports, and how packages organise large code bases.

Beginner 10 min read·Lesson 215 of 306 in Python Programming

Learning objectives

  • Create a package with modules
  • Import from packages and subpackages
  • Use relative imports inside a package

Definition

A package is a directory of modules that is imported as a unit. Modules inside are accessed with dotted names such as shop.pricing, and packages can contain subpackages to any depth.

Introduction

When a project grows beyond a handful of modules, folders keep it organised. In Python, a folder of modules is a package.

Why it matters

Packages give large projects structure and avoid name clashes: shop.models.product and blog.models.product can coexist.

Detailed explanation

A package is a folder containing modules, normally with an __init__.py file (see the next lesson).

Import modules with dotted names: import shop.pricing, from shop import pricing, or from shop.pricing import with_tax.

Packages can contain subpackages: shop/models/product.py is imported as shop.models.product.

Absolute imports use the full dotted path from the top-level package and are the clearest choice.

Inside a package, relative imports use dots: from . import pricing (same package) or from ..models.product import Product (parent package). They only work in modules imported as part of a package.

Package objects have a __path__ attribute listing their folder(s); plain modules don't.

Many standard modules are packages: json, email, http, urllib and concurrent.

The folder that contains the top-level package must be on sys.path. When you run a script or use python -m from the project folder, that happens automatically.

Syntax

Python
# shop/
# __init__.py
# pricing.py
# models/__init__.py
# models/product.py
from shop import pricing
from shop.models.product import Product
  • A package is a folder of modules.
  • Use dotted names to import.
  • Relative imports work inside packages.

Code examples

A simple package

Python
from pathlib import Path
import importlib
pkg = Path("shop")
pkg.mkdir()
(pkg / "__init__.py").write_text("", encoding="utf-8")
(pkg / "pricing.py").write_text('''def with_tax(amount, rate=0.18):
return round(amount * (1 + rate), 2)
''', encoding="utf-8")
importlib.invalidate_caches()
from shop import pricing
from shop.pricing import with_tax
print(pricing.with_tax(100), with_tax(250, 0.05))
Output
118.0 262.5

Standard packages

Python
import json
import json.decoder
print(hasattr(json, "__path__"), hasattr(json.decoder, "__path__"))
print(json.decoder.__name__, json.decoder.__package__)
Output
True False
json.decoder json

More examples

Subpackages and relative imports

Python
from pathlib import Path
import importlib
files = {
"shop/__init__.py": "",
"shop/models/__init__.py": "",
"shop/models/product.py": '''class Product:
def __init__(self, name, price):
self.name, self.price = name, price
''',
"shop/services/__init__.py": "",
"shop/services/cart.py": '''from ..models.product import Product
def total(items):
return sum(Product(n, p).price for n, p in items)
''',
}
for rel, src in files.items():
path = Path(rel)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(src, encoding="utf-8")
importlib.invalidate_caches()
from shop.services.cart import total
print(total([("pen", 20), ("book", 250)]))
import shop.models.product as product_module
print(product_module.__name__)
Output
270
shop.models.product

Step-by-step explanation

  • The services subpackage imports from its sibling models with a relative import (two dots = parent package).
  • The top-level script uses absolute dotted imports.
  • An alias keeps a long dotted module name short.

Expected output

Running “Subpackages and relative imports” prints exactly:

TextOutput
270
shop.models.product

Practical applications

  • Django projects split into apps, each a package.
  • Libraries like requests organised into several modules inside one package.

Best practices

  • Group related modules into packages.
  • Prefer absolute imports for clarity.
  • Run package modules with python -m.

Common mistakes

Running a package module directly

Avoid

python shop/services/cart.py # relative import fails

Prefer

python -m shop.services.cart

Relative imports need the module to be loaded as part of its package.

Important notes

  • Folders without __init__.py can still be imported as 'namespace packages', mainly used to split one package across several locations.

Key takeaways

  • A package is a folder of modules.
  • Import with dotted names.
  • Relative imports use dots inside packages.

Try it yourself

  1. 1
    Create a school package with students.py and grades.py and import from both.
  2. 2
    Add a subpackage reports with a module that imports from school.grades using a relative import.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions cover the “Python Modules and Packages” module. Answers and explanations are revealed after you submit.

  • ModerateWhat happens the second time a module is imported in the same program?
  • ModerateCode under if __name__ == "__main__": runs when…
  • ModerateWhat is printed?
Practise this module