Course contentsShow
← Python
Lesson 513 of 1,0608. Professional Tooling and PackagingFree lesson

Adopting the Src-Layout Pattern

You will restructure your codebase by moving application logic into a dedicated src directory to prevent accidental imports of uninstalled modules.

In this lesson, you will learn how to protect your production imports by restructuring your project into a src-layout, ensuring your tests only run against the code that is actually installed in your environment.

The Problem: Implicit Import Paths

In a standard flat project structure, Python adds the project root to sys.path. This creates a dangerous "hidden" behavior: if you have a folder named my_package at the root, your scripts can import it even if the package isn't properly installed. This leads to "it works on my machine" bugs where local files mask installed dependencies, or tests pass despite missing critical metadata in your pyproject.toml or setup.py.

The Solution: The src Layout

The src-layout moves your actual package code into a subdirectory named src. This creates a physical barrier: Python cannot accidentally import your code unless it is explicitly installed into the environment's site-packages directory.

Consider this transition:

Before (Flat Layout):

project_root/
├── my_app/        <-- Importable from root!
│   └── logic.py
└── tests/

After (Src Layout):

project_root/
├── src/
│   └── my_app/    <-- Protected
│       └── logic.py
├── tests/         <-- Must "pip install -e ." to import my_app
└── pyproject.toml

Why This Matters

By forcing yourself to run pip install -e . (editable install) to work on your code, you ensure that your development environment behaves exactly like your production environment. If you add a new sub-module or a dependency, the code will only be available to your tests or scripts if it is correctly defined in your packaging configuration. This eliminates the risk of accidentally relying on local file structures that won't exist once the project is deployed or installed by another user. It turns packaging from an afterthought into a requirement for development.

Key Takeaway: Adopting the src-layout forces your project to be "installed" to be usable, ensuring your local development environment accurately reflects how your code will perform in production.