Intermediate Chapter 91 · 25 min read · Module 7: Python Modules and Packages
Python Packages
- After this chapter you can explain the difference between a module and a package.
- You can create a package folder with an __init__.py file and import from it.
- You can write absolute and relative imports between modules of the same package.
- You can use __init__.py to give a package a clean public interface.
- You can describe what a namespace package is and list the modules inside a package.
When a project grows, one folder full of modules becomes hard to manage. A package solves this by grouping related modules inside a folder, in the same way that folders group files on your computer. Big libraries such as the ones you will install with pip are almost always packages.
A package gives you a dotted name for each module, like shop.prices or shop.tools.text. These dotted names show how the code is organised and also prevent clashes: two different packages can each have a module called utils without any problem, because their full names differ.
In this chapter you will build small packages from code, so every example can run on its own. You will learn what the special file __init__.py does, how modules inside one package find each other, and how to design a package so that its users can write short and friendly imports.
Module or package?
A module is a single file and a package is a folder. A package can also contain other packages, called subpackages, and so form a tree. The top of the tree is the package you import first. For example, a folder layout like the one below gives the module names shop, shop.prices and shop.tools.text.
| Path on disk | Name you import |
|---|---|
| shop/__init__.py | shop |
| shop/prices.py | shop.prices |
| shop/tools/__init__.py | shop.tools |
| shop/tools/text.py | shop.tools.text |
Your first package
To create a package you make a folder and put a file named __init__.py inside it. The file may be empty. Python runs it the first time the package is imported. The examples in this chapter use a small helper called make that writes a set of files, so that each example builds its own folder structure.
import sys
sys.path.insert(0, ".")
from pathlib import Path
def make(files):
for name, text in files.items():
p = Path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
make({
"shop/__init__.py": "",
"shop/prices.py": "def with_tax(x):\n return round(x * 1.1, 2)\n",
})
import shop.prices
from shop import prices
print(shop.prices.with_tax(100))
print(prices.with_tax(50))
print(prices.__name__)Notice that import shop.prices makes the name shop available, and you reach the function through the full dotted path. The form from shop import prices gives you the module under the short name prices. Both refer to the same module object.
What __init__.py does
The __init__.py file runs when the package is first imported, and the names it defines become attributes of the package. You can leave it empty, or use it to set up the package. A popular use is to import the most useful names from inner modules so users do not need to know the internal layout.
import sys
sys.path.insert(0, ".")
from pathlib import Path
def make(files):
for name, text in files.items():
p = Path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
make({
"geo/__init__.py": "from .shapes import area\nfrom .units import CM\n\n__all__ = [\"area\", \"CM\"]\nprint(\"geo ready\")\n",
"geo/shapes.py": "def area(w, h):\n return w * h\n",
"geo/units.py": "CM = \"centimetres\"\n",
})
import geo
print(geo.area(3, 5))
print(geo.CM)
print(sorted(geo.__all__))With this design the user writes geo.area(3, 5) instead of geo.shapes.area(3, 5). If you later move area to a different file inside the package, user code still works, because only __init__.py has to change.
Absolute and relative imports
Inside a package, one module often needs another. There are two ways to write the import. An absolute import gives the full path starting from the top package, such as from app.core.helpers import clean. A relative import uses dots: one dot means the current package, two dots mean the parent package. For instance from .helpers import clean means the module helpers in the same package.
| Syntax | Meaning |
|---|---|
| from . import x | module x in the current package |
| from .x import y | name y from module x in the current package |
| from .. import x | module x in the parent package |
| from ..core.x import y | name y from core.x in the parent package |
Absolute imports are clear and easy to search for, and the Python style guide prefers them. Relative imports are shorter and keep working if you rename the top package. A relative import only works inside a package, not in a plain script that you run directly.
import sys
sys.path.insert(0, ".")
from pathlib import Path
def make(files):
for name, text in files.items():
p = Path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
make({
"app/__init__.py": "",
"app/core/__init__.py": "",
"app/core/helpers.py": "def clean(s):\n return s.strip().lower()\n",
"app/core/engine.py": "from .helpers import clean\n\ndef run(s):\n return clean(s) + \"!\"\n",
"app/tools/__init__.py": "",
"app/tools/cli.py": "from app.core.engine import run\nfrom ..core.helpers import clean\n\ndef main():\n return run(\" HELLO \"), clean(\" X \")\n",
})
from app.tools import cli
print(cli.main())The module engine uses a relative import to reach helpers next to it. The module cli shows both styles: an absolute import of engine and a relative import with two dots that climbs to the parent package app.
Looking inside a package
You can ask Python what modules a package contains with pkgutil.iter_modules. It needs the package's __path__ list, which every package has. The result is useful for plugin systems that load every module of a folder.
import sys
sys.path.insert(0, ".")
from pathlib import Path
def make(files):
for name, text in files.items():
p = Path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
import pkgutil
make({
"plug/__init__.py": "",
"plug/alpha.py": "NAME = \"alpha\"\n",
"plug/beta.py": "NAME = \"beta\"\n",
"loose/gamma.py": "NAME = \"gamma\"\n",
})
import plug
import loose.gamma
names = sorted(m.name for m in pkgutil.iter_modules(plug.__path__))
print(names)
print(loose.gamma.NAME)
print(loose.__file__ is None)The folder loose has no __init__.py, yet it can still be imported. Since Python 3.3 such a folder is a namespace package. It works for simple cases, but it has no place to run setup code, and its __file__ is None. For ordinary projects, always add an __init__.py so that your intention is clear and tools treat the folder as a package.
Designing a good package
- Choose a short, lowercase name that will not clash with a standard library module.
- Group modules by purpose, not by type of object: use
billingandreports, notfunctionsandclasses. - Keep the tree shallow. Two or three levels are usually enough.
- Re-export the main names in
__init__.pyand list them in__all__. - Avoid circular imports between modules of the same package; move shared code to a common module.
- Keep the import of heavy or slow libraries inside the functions that need them if they are rarely used.
Python syntax
package/
__init__.py
module.pyimport package.modulefrom package import modulefrom package.module import namefrom . import siblingfrom ..parent_pkg import otherReal-world applications
- Organising a medium or large application into areas such as database, web and utilities.
- Distributing a reusable library so that others can install it.
- Building plugin systems that load every module in a folder.
- Keeping tests, scripts and application code separate but connected by clear imports.
- Reading and understanding open source projects, which are almost always packages.
Common mistakes
Fix: Add an __init__.py file, even if it is empty, to each package folder.
Fix: Run it as a module from the project root: python -m app.core.engine.
Fix: Pick a distinctive name so that your package does not hide the standard one.
Fix: Move the shared code into a third module, or import inside the function that needs it.
Fix: Keep __init__.py light: re-exports and small setup only.
Important tips
- Use absolute imports for clarity unless a relative import is clearly simpler.
- Use python -m package.module to run modules that use relative imports.
- Check pkgutil.iter_modules(package.__path__) when you need to discover modules.
- Write a short docstring at the top of __init__.py to describe the package.
Key points summary
- A package is a folder of modules, usually with an __init__.py file.
- __init__.py runs on first import and defines the package's own names.
- Dotted names such as shop.prices follow the folder tree.
- Relative imports use dots and work only inside packages.
- A folder without __init__.py can be a namespace package.
Exam and interview points
- Package = folder; module = file.
- __init__.py is executed once when the package is first imported.
- from . import x is a relative import; it fails outside a package.
- __all__ in __init__.py controls a star import of the package.
- Namespace packages have no __init__.py and their __file__ is None.
Quick revision
- Folder + __init__.py = package.
- Dots show the folder tree: a.b.c.
- One dot = this package, two dots = parent.
- Re-export names in __init__.py for a clean interface.
- Run package modules with python -m.
- Namespace package: no __init__.py.
Frequently asked questions
Is __init__.py still required?
Not strictly. Python 3.3 and later allow namespace packages without it. It is still the best habit, because it makes the folder a regular package and gives you a place for setup code.
What is the difference between import a.b and from a import b?
The first binds the name a and you write a.b. The second binds only b. Both load the same module.
Why does my relative import fail with an error?
You probably ran the file directly as a script. Relative imports need the file to be part of a package, so run it with python -m package.module.
How do I import every module in a package?
Either import them in __init__.py, or discover them with pkgutil.iter_modules and import each one with importlib.import_module.
Can a package contain another package?
Yes. A subpackage is just a folder with its own __init__.py inside the main package, and it has a dotted name like shop.tools.
Practise this chapter
16 practice questions Take the chapter quiz