Python project structure is an important part of building applications that remain understandable as the codebase grows. A small Python script can work perfectly as a single file, but larger applications benefit from clear boundaries between application logic, configuration, tests, dependencies, and reusable modules.
Good project structure is not about following one rigid folder layout. The right structure depends on whether you are building a command-line tool, web API, library, data-processing application, automation script, or larger service. The goal is to make responsibilities obvious, imports predictable, testing straightforward, and future changes safer.
A useful Python project should make it easy for a developer to answer simple questions: Where does the application start? Where is business logic located? Where are tests? Where are configuration settings defined? Which dependencies are required? Which files are safe to change independently?
What You Will Learn
- How to organize Python modules and packages
- How a scalable project directory can be structured
- How to separate application, domain, and infrastructure concerns
- How to organize tests and test fixtures
- How configuration and environment variables fit into a project
- How dependency files support reproducible environments
- How __main__.py and package entry points work
- Common project-structure mistakes and maintainable alternatives
Why Project Structure Matters
When a project is small, all of its code may fit comfortably inside one file. As functionality grows, putting everything in that file creates problems. Database code can become mixed with business rules, utility functions can become shared by unrelated features, and tests become difficult to locate.
A clear structure reduces these problems by giving different responsibilities a predictable home. It also makes onboarding easier because developers can understand the application from its directory layout before reading every implementation detail.
A Simple Python Project
A small command-line project may only need a few files:
my_project/
├── app.py
├── requirements.txt
└── README.md
This is perfectly reasonable for a small utility. The mistake is assuming that every project should remain this simple regardless of its size.
A More Scalable Structure
A larger application can separate source code, tests, configuration, and documentation more clearly.
my_project/
├── pyproject.toml
├── README.md
├── .gitignore
├── src/
│ └── my_project/
│ ├── __init__.py
│ ├── __main__.py
│ ├── config.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ ├── services/
│ │ ├── __init__.py
│ │ └── user_service.py
│ └── repositories/
│ ├── __init__.py
│ └── user_repository.py
└── tests/
├── test_user.py
└── test_user_service.py
This layout separates the installable application package from tests and project-level configuration. The exact folders should change with the application's needs rather than being copied mechanically.
Modules and Packages
A module is typically a Python file containing code that can be imported. A package is a collection of modules organized under a package namespace.
my_project/
└── app/
├── __init__.py
├── users.py
└── orders.py
Here,
users.py
and
orders.py
are modules inside the
app
package.
What __init__.py Does
An
__init__.py
file can define package initialization behavior and package-level names. Modern Python also supports namespace packages without requiring this file in every package directory, but many application projects still use
__init__.py
to make package boundaries explicit and to support package-level exports or initialization where appropriate.
app/
├── __init__.py
├── users.py
└── orders.py
Keep package initialization lightweight. Heavy startup logic inside
__init__.py
can make imports slower and create unexpected side effects.
The src Layout
The
src/
layout places the actual importable application package under a dedicated source directory.
my_project/
├── pyproject.toml
├── README.md
├── src/
│ └── my_project/
│ ├── __init__.py
│ └── cli.py
└── tests/
└── test_cli.py
This structure helps separate project metadata and tests from the actual package source. It is commonly used for Python libraries and applications that are packaged for installation.
The Application Entry Point
Every executable application needs a clear starting point. Depending on the project, that entry point may be a module, a function, a command-line script, or a web-server startup configuration.
A common Python package pattern is
__main__.py:
my_project/
└── src/
└── my_project/
├── __init__.py
└── __main__.py
Example:
# __main__.py
def main():
print("Application started")
if __name__ == "__main__":
main()
This allows the package to provide a clear executable entry point when invoked as a module.
Keep the Entry Point Small
The application's entry point should usually coordinate startup rather than contain all business logic.
from .services.user_service import UserService
def main():
service = UserService()
service.run()
if __name__ == "__main__":
main()
This keeps startup code separate from reusable application behavior and makes the underlying service easier to test.
Organizing by Responsibility
One common way to structure larger applications is to separate code according to responsibility.
Models
Data structures and domain entities used throughout the application.
Services
Business operations that coordinate domain behavior.
Repositories
Persistence and data-access operations where this boundary is useful.
API or CLI
External interfaces through which users or other systems interact with the application.
This style can work well, but it should not become a collection of arbitrary folders. A small application may not need separate repository, service, and domain layers.
Organizing by Feature
Another useful approach is organizing a larger application by business feature rather than technical layer.
src/
└── my_project/
├── users/
│ ├── models.py
│ ├── service.py
│ └── repository.py
├── orders/
│ ├── models.py
│ ├── service.py
│ └── repository.py
└── payments/
├── models.py
├── service.py
└── gateway.py
Feature-oriented organization keeps related code close together. This can become particularly useful when each feature grows into a substantial part of the application.
Layered vs Feature-Based Structure
| Approach | Typical Organization | Good Fit |
|---|---|---|
| Layered | models, services, repositories, API | Applications with clear technical boundaries. |
| Feature-based | users, orders, payments | Applications organized around business capabilities. |
| Hybrid | Features containing focused technical layers | Larger systems where both boundaries matter. |
Separating Business Logic from Infrastructure
A maintainable application usually benefits from keeping core business rules independent from infrastructure details such as database clients, HTTP libraries, filesystem APIs, or framework-specific request objects.
src/
└── app/
├── domain/
│ ├── models.py
│ └── rules.py
├── services/
│ └── user_service.py
└── infrastructure/
├── database.py
└── http_client.py
This separation means a business rule can often be tested without starting a database, network server, or other external infrastructure.
Configuration Management
Configuration should be separated from business logic. Settings such as database connection details, API endpoints, feature switches, or runtime modes should not be scattered throughout application modules.
src/
└── my_project/
├── config.py
├── services/
└── models/
Environment variables are commonly used for deployment-specific configuration. Sensitive credentials should not be hard-coded in source files or committed to version control.
Configuration vs Secrets
Not every configuration value is a secret. A default port or feature flag can often be safely represented in code or configuration files, while passwords, tokens, and private credentials should be provided through an appropriate secret-management mechanism.
Keeping this distinction clear prevents developers from turning configuration files into uncontrolled collections of sensitive data.
The pyproject.toml File
Modern Python projects commonly use
pyproject.toml
as the central project configuration file. It can contain project metadata, dependency declarations, build configuration, and configuration for development tools depending on the project's tooling choices.
[project]
name = "my-project"
version = "0.1.0"
description = "Example Python application"
requires-python = ">=3.12"
dependencies = [
"requests"
]
The exact metadata and dependency configuration depends on the packaging and build tools being used. The important project-structure idea is to keep project metadata and dependency declarations in a predictable project-level location.
Requirements Files
Some projects still use requirement files such as
requirements.txt
to describe installable dependencies. This can be practical for applications and deployment workflows even when the project also uses
pyproject.toml.
requirements.txt
requests
python-dateutil
Choose a dependency-management approach that fits the project and use it consistently. Avoid maintaining multiple dependency sources manually when they can easily drift apart.
The Tests Directory
Tests should have a predictable location. A top-level
tests/
directory is a common choice.
my_project/
├── src/
│ └── my_project/
│ ├── users.py
│ └── orders.py
└── tests/
├── test_users.py
└── test_orders.py
Test files should usually mirror important application boundaries without reproducing the entire production directory tree unnecessarily.
Testing by Behavior
Good test organization focuses on behavior rather than simply matching every production file one-to-one. A service with several business rules can have tests grouped around those rules and important edge cases.
tests/
├── test_user_creation.py
├── test_user_validation.py
└── test_user_permissions.py
The exact organization can vary. The important principle is that a developer should be able to locate relevant tests quickly.
Test Fixtures and Shared Test Utilities
Larger test suites often contain reusable fixtures or helper functions. These should be kept separate from production application code.
tests/
├── conftest.py
├── fixtures/
│ └── users.py
├── test_users.py
└── test_orders.py
The exact fixture structure depends on the testing framework and project complexity. Avoid turning a test helper module into a second uncontrolled utility package.
Utility Modules
Utility modules can be useful for genuinely reusable operations, but a folder named
utils
can easily become a dumping ground for unrelated functions.
Prefer names that explain responsibility. Instead of putting everything inside
utils.py,
consider focused modules such as
date_formatting.py,
validation.py,
or
serialization.py
when those boundaries are meaningful.
Avoid Circular Imports
Poor project structure can create circular imports where module A imports module B while module B also imports module A. This often signals that responsibilities are too tightly coupled.
# users.py
from orders import Order
# orders.py
from users import User
Rather than trying to work around every circular import, examine whether shared models, protocols, interfaces, or orchestration logic should move to a better-defined boundary.
Relative vs Absolute Imports
Within a package, both absolute and relative imports can be useful. Absolute imports make the source package explicit, while relative imports can be convenient for closely related modules.
# Absolute
from my_project.services.user_service import UserService
# Relative
from .user_service import UserService
Choose a consistent style for the project. Avoid import patterns that depend on the current working directory in fragile ways.
Naming Files and Modules
Module and package names should be short, descriptive, and consistent. Python module filenames are commonly written in lowercase with underscores where necessary.
user_service.py
order_repository.py
email_client.py
date_utils.py
Avoid vague names that provide little information about responsibility. Clear names make imports and code navigation easier.
README.md
A good
README.md
should help a new developer understand what the project does and how to run it.
Useful sections often include a project overview, setup instructions, environment requirements, running the application, testing, and important development notes. Keep the README focused on the information someone needs to successfully work with the project.
The .gitignore File
Generated files, virtual environments, caches, local configuration, and secrets should generally not be committed to version control. A Python project commonly ignores items such as:
__pycache__/
*.py[cod]
.venv/
.env
.pytest_cache/
.mypy_cache/
dist/
build/
*.egg-info/
The exact entries depend on the project's tools and generated artifacts.
Environment Files
Local development often uses a
.env
file or another environment-specific mechanism for configuration values. Keep environment-specific files out of source control when they contain secrets or machine-specific values.
The repository should normally provide an example or documentation showing which variables are required, without committing real credentials.
A Web API Project Structure
A Python web API might use a structure similar to:
my_api/
├── pyproject.toml
├── README.md
├── .gitignore
├── src/
│ └── my_api/
│ ├── __init__.py
│ ├── main.py
│ ├── config.py
│ ├── api/
│ │ ├── __init__.py
│ │ └── users.py
│ ├── models/
│ │ ├── __init__.py
│ │ └── user.py
│ ├── services/
│ │ ├── __init__.py
│ │ └── user_service.py
│ └── repositories/
│ ├── __init__.py
│ └── user_repository.py
└── tests/
├── test_users_api.py
└── test_user_service.py
The API layer handles external requests, services hold application operations, repositories isolate persistence concerns, and models represent structured data. The exact boundaries will depend on the framework and application.
A CLI Project Structure
A command-line application can often remain much simpler:
task_tool/
├── pyproject.toml
├── README.md
├── src/
│ └── task_tool/
│ ├── __init__.py
│ ├── __main__.py
│ ├── cli.py
│ └── tasks.py
└── tests/
├── test_cli.py
└── test_tasks.py
This demonstrates an important principle: project structure should scale with complexity. A command-line utility does not automatically need a dozen architectural layers.
A Library Project Structure
A reusable Python library should make its public API clear and keep implementation modules behind that interface.
my_library/
├── pyproject.toml
├── README.md
├── src/
│ └── my_library/
│ ├── __init__.py
│ ├── client.py
│ ├── models.py
│ └── internal/
│ ├── __init__.py
│ └── transport.py
└── tests/
├── test_client.py
└── test_models.py
Public classes and functions should have stable names and behavior, while internal modules can remain implementation details that are free to change more easily.
Avoid One Giant Module
A common early-stage pattern is one large module containing models, API calls, business rules, utility functions, configuration, and startup logic. This may work initially but eventually makes the module difficult to navigate and test.
Split a module when there is a meaningful responsibility boundary, not simply when it reaches an arbitrary number of lines.
Avoid Excessive Fragmentation
The opposite problem is creating dozens of tiny files that each contain one or two functions without a meaningful reason. Excessive fragmentation forces developers to jump between many modules to understand a simple operation.
A good project structure balances separation with locality. Related code should be easy to find and understand without unnecessary navigation.
Dependency Direction
In larger applications, it helps to think about which modules are allowed to depend on which others. For example, a service layer may depend on a repository interface without forcing the domain model to import a database client.
API / CLI
Receives external input and invokes application operations.
Services
Coordinates application and business operations.
Domain / Models
Represents core application concepts and rules.
Infrastructure
Handles databases, external APIs, files, and other concrete resources.
This is a design guideline rather than a mandatory architecture. Small applications can simplify these boundaries significantly.
Practical Example: User Management
Consider a simple application that creates users. A clean boundary might separate the data model, repository, service, and entry point.
models.py
from dataclasses import dataclass
@dataclass
class User:
name: str
email: str
repository.py
class UserRepository:
def __init__(self):
self.users = []
def save(self, user):
self.users.append(user)
return user
service.py
from .models import User
class UserService:
def __init__(self, repository):
self.repository = repository
def create_user(
self,
name: str,
email: str
) -> User:
if not name.strip():
raise ValueError(
"Name is required"
)
user = User(
name=name,
email=email
)
return self.repository.save(user)
main.py
from .repository import UserRepository
from .service import UserService
def main():
repository = UserRepository()
service = UserService(repository)
user = service.create_user(
"Alex",
"alex@example.com"
)
print(user)
if __name__ == "__main__":
main()
The example is intentionally small. Its main value is the separation of responsibilities: the model represents data, the repository handles persistence, the service contains application rules, and the entry point coordinates execution.
Project Structure and Testing
Good project boundaries make testing easier because individual components can be tested independently. For example, a service can receive a simple fake repository instead of requiring a real database.
class FakeRepository:
def __init__(self):
self.saved_users = []
def save(self, user):
self.saved_users.append(user)
return user
def test_user_creation():
repository = FakeRepository()
service = UserService(repository)
user = service.create_user(
"Alex",
"alex@example.com"
)
assert user.name == "Alex"
assert len(repository.saved_users) == 1
The exact testing syntax depends on the framework being used, but the structural idea remains the same: isolate business behavior from external dependencies when practical.
Common Project Structure Mistakes
Everything in one file
Fine for tiny scripts, but increasingly difficult to maintain as unrelated responsibilities accumulate.
Everything in utils
A generic utility module often becomes a dumping ground for unrelated behavior.
Overengineering layers
Small applications do not automatically need repositories, factories, interfaces, and multiple service layers.
Circular dependencies
Circular imports often indicate that responsibilities or dependency directions need to be reconsidered.
Secrets in source control
Credentials and private configuration should not be hard-coded or committed to the repository.
Unclear entry point
Developers should be able to determine quickly how the application is started.
Best Practices for Python Project Structure
- Start with the simplest structure that fits the current project size.
- Split modules when a meaningful responsibility boundary appears.
- Keep the application entry point small and focused on startup orchestration.
- Separate tests from production code and make them easy to discover.
- Keep configuration centralized instead of scattering settings across modules.
- Keep secrets out of source control and provide a documented configuration contract.
- Use meaningful module names instead of generic dumping-ground modules.
- Keep dependency direction understandable and avoid circular imports.
- Use the
src/layout when it provides useful package isolation for the project. - Organize by technical layer, business feature, or a deliberate hybrid based on the application's complexity.
- Do not introduce architectural layers that the project does not actually need.
A Practical Production-Oriented Layout
A medium-sized Python service might eventually look like this:
project/
├── pyproject.toml
├── README.md
├── .gitignore
├── .env.example
├── src/
│ └── project/
│ ├── __init__.py
│ ├── __main__.py
│ ├── config.py
│ ├── api/
│ │ ├── __init__.py
│ │ ├── users.py
│ │ └── orders.py
│ ├── domain/
│ │ ├── __init__.py
│ │ ├── user.py
│ │ └── order.py
│ ├── services/
│ │ ├── __init__.py
│ │ ├── user_service.py
│ │ └── order_service.py
│ ├── repositories/
│ │ ├── __init__.py
│ │ ├── user_repository.py
│ │ └── order_repository.py
│ └── infrastructure/
│ ├── __init__.py
│ ├── database.py
│ └── external_api.py
└── tests/
├── test_user_service.py
├── test_order_service.py
└── test_api.py
This is not a template that every Python project should copy. It is an example of how responsibilities can be separated as the system grows. In a small project, several of these directories may be unnecessary.
How to Evolve a Project Structure
Project structure should evolve with the application. Starting with ten architectural layers on the first day creates overhead before the problem exists. Starting with one giant file and refusing to split it creates the opposite problem later.
A better approach is incremental. Begin with a small module, identify responsibilities as the code grows, extract cohesive modules, and introduce package boundaries when they make dependencies or ownership clearer.
Interview Questions to Prepare
- How would you structure a Python project?
- What is the difference between a module and a package?
- What is the purpose of
__init__.py? - What is
__main__.pyused for? - Why is a
src/layout useful? - How would you separate business logic from infrastructure code?
- How should tests be organized in a Python project?
- How would you manage configuration and secrets?
- Why do circular imports occur and how can project structure prevent them?
- When would you choose feature-based organization over layered organization?
Summary
A good Python project structure creates clear boundaries without adding unnecessary complexity. Modules should have understandable responsibilities, packages should represent meaningful groups of functionality, tests should be easy to locate, configuration should have a clear home, and the application's entry point should remain focused.
As applications grow, you can separate domain logic, services, repositories, API interfaces, and infrastructure or organize the code around business features. Neither approach is universally correct. The strongest project structures evolve with the application and optimize for clear ownership, predictable imports, testability, and ease of maintenance.