Sub topic 12
Project layout and installing your package
This chapter assumes you can write functions and classes, run scripts from a terminal, and have read the earlier chapters on sys.path, packages, relative imports, and __all__. Here you will put those pieces together into a project that you can import from anywhere, test, and share.
Why layout matters
Imports work in a quick experiment because Python puts the script's directory at the front of sys.path. That is convenient, and it hides problems. Code that runs from the project root may fail from any other directory. Tests may pass because they import the files in your working tree, not the code a user would install.
Two decisions fix most of this:
- Where the package directory sits relative to the repository root.
- Whether the package is installed into the environment, so
sys.pathfinds it without tricks.
Two common layouts
In a flat layout, the package sits next to the project files at the root. In a src layout, it sits one level down inside src/.
# flat layout
myproj/
pyproject.toml
shapes/
__init__.py
circle.py
tests/
test_circle.py
# src layout
myproj/
pyproject.toml
src/
shapes/
__init__.py
circle.py
tests/
test_circle.py| Aspect | Flat layout | Src layout |
|---|---|---|
| Package importable from the repo root without installing | Yes | No |
| Tests exercise the installed code | Only if you take care | Yes, by default |
| Risk of importing the wrong copy | Higher | Lower |
| Setup effort | Lowest | One extra directory |
The flat layout is fine for small scripts and applications. The src layout is the safer default for anything you plan to distribute. When you run python or pytest from the repo root in a flat layout, the root is on sys.path, so import shapes succeeds even if the package is broken or missing from the installed metadata. With a src layout, import shapes fails until you install the project. That failure is useful, because it shows you the same problem a user would hit.
Describing the project with pyproject.toml
pyproject.toml is the standard file that tells build tools what your project is. A minimal one for the src layout looks like this:
[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"
[project]
name = "shapes-demo"
version = "0.1.0"
description = "Small geometry helpers"
requires-python = ">=3.9"
dependencies = []
[tool.setuptools.packages.find]
where = ["src"]Three details are worth knowing:
nameunder[project]is the distribution name, which is what you type afterpip install. The import name is the directory name undersrc/. They often match, but they do not have to. This project installs asshapes-demoand imports asshapes.[build-system]names the tool that builds the project. Setuptools is one choice. Hatchling, Flit, and others use the same[project]table.where = ["src"]tells setuptools to look for packages undersrc/. Without it, setuptools searches the project root and does not find your package.
Installing in editable mode
During development you want edits to take effect without reinstalling. An editable install does this. Create a virtual environment, then install the project in editable mode:
python -m venv .venv
source .venv/bin/activate
python -m pip install -e .On Windows, activate with .venv\Scripts\activate. Running pip as python -m pip guarantees that it installs into the same interpreter you are running.
After this, import shapes works from any directory while the environment is active. You can check where Python found it:
import shapes
import sys
print(shapes.__file__)
print(any("site-packages" in p for p in sys.path))For an editable install, shapes.__file__ points into your src/ directory, not into site-packages. Python resolves the name through a small file in site-packages that redirects to your source tree. Edits to existing files appear immediately. If you add new top-level packages or change pyproject.toml, reinstall.
A regular install, python -m pip install ., copies the files into site-packages. Use it to confirm that the copy a user would receive actually works.
Putting it together: a working project
Use the shapes package from earlier chapters. Create these files:
myproj/
pyproject.toml
src/
shapes/
__init__.py
__main__.py
circle.py
util/
__init__.py
mathx.py
tests/
test_circle.pysrc/shapes/util/mathx.py:
def square(x):
return x * xsrc/shapes/circle.py:
from .util.mathx import square
def area(r):
return 3.14159 * square(r)src/shapes/__init__.py:
from .circle import area as circle_area
__all__ = ["circle_area"]src/shapes/__main__.py:
import sys
from shapes import circle_area
def main(argv=None):
args = sys.argv[1:] if argv is None else argv
radius = float(args[0]) if args else 1.0
print(circle_area(radius))
if __name__ == "__main__":
main()tests/test_circle.py:
from shapes import circle_area
def test_circle_area_of_unit_circle():
assert abs(circle_area(1) - 3.14159) < 1e-9After python -m pip install -e ., run the package and the tests from any directory:
python -m shapes 2
python -m pytestThe first command prints 12.56636. It works because python -m shapes runs shapes/__main__.py as a script while still treating shapes as a package. The test imports shapes the same way a user would, with no sys.path edits.
Avoiding sys.path hacks
A common shortcut is to add the source directory to the path at the top of a test or script:
import sys
sys.path.insert(0, "../src")This works only when the working directory happens to be right, since "../src" is resolved relative to where you run the command. It also hides installation problems. If you find yourself writing it, install the project in editable mode instead. The same goes for the PYTHONPATH environment variable: it is acceptable for a one-off check, but it is not part of the project, and a teammate will not have it set.
Common errors
ModuleNotFoundError: No module named 'shapes'after creating the files. The package is not installed in the active environment. Check withpython -m pip list, and confirm that thepythonyou run is the one inside.venv.- The package installs but is empty or missing. In a src layout, the
where = ["src"]setting is missing, or__init__.pyis absent from a subpackage. Setuptools'findonly collects directories that are regular packages. To pick up namespace packages, usefind_namespaceinstead. - You edit a file and see old behavior. Either you did a regular install, which copied the files, or a running interpreter still holds the old module in
sys.modules. Restart the interpreter or reinstall. - Relative import fails when you run a file directly. Running
python src/shapes/circle.pymakescircle.pythe__main__module with no parent package, sofrom .util.mathx import squareraisesImportError. Usepython -m shapes.circleor an installed entry point instead. - A test imports a different copy than you expect. Print
shapes.__file__to see which copy won onsys.path.
Summary of decisions
- Use a src layout for anything you will share, and a flat layout only for small, local code.
- Describe the project in
pyproject.toml, keeping the distribution name and the import name distinct in your mind. - Work inside a virtual environment, and install with
python -m pip install -e .. - Import your own package by its absolute name, and use relative imports only inside the package.
- Treat
sys.pathedits as a sign that the project is not installed.
Exercise
You have a src layout with src/shapes/ and a pyproject.toml, and you have not run any install command. From the repo root, python -c "import shapes" raises ModuleNotFoundError. Name the cause and give the command that fixes it. Then explain why the same import would succeed without installing if the package sat directly in the repo root.
Show answer
The package is not on sys.path, because it lives under src/ and has not been installed into the active environment. Run python -m pip install -e . inside the activated virtual environment. In a flat layout, python -c puts the current directory (the repo root) at the front of sys.path, so shapes is found there without any installation.
Exercise
A project's pyproject.toml has name = "shapes-demo", and the package directory is src/shapes/. What do you type to install it and what do you type to import it? Then name the one setting needed so setuptools finds the package under src/.
Show answer
Install with python -m pip install shapes-demo (or python -m pip install -e . from the project directory), and import with import shapes. The setting is where = ["src"] under [tool.setuptools.packages.find].