1
---
2
name: python-project-structure
3
description: Python project organization, module architecture, and public API design. Use when setting up new projects, organizing modules, defining public interfaces with __all__, or planning directory layouts.
4
---
5
6
# Python Project Structure & Module Architecture
7
8
Design well-organized Python projects with clear module boundaries, explicit public interfaces, and maintainable directory structures. Good organization makes code discoverable and changes predictable.
9
10
## When to Use This Skill
11
12
- Starting a new Python project from scratch
13
- Reorganizing an existing codebase for clarity
14
- Defining module public APIs with `__all__`
15
- Deciding between flat and nested directory structures
16
- Determining test file placement strategies
17
- Creating reusable library packages
18
19
## Core Concepts
20
21
### 1. Module Cohesion
22
23
Group related code that changes together. A module should have a single, clear purpose.
24
25
### 2. Explicit Interfaces
26
27
Define what's public with `__all__`. Everything not listed is an internal implementation detail.
28
29
### 3. Flat Hierarchies
30
31
Prefer shallow directory structures. Add depth only for genuine sub-domains.
32
33
### 4. Consistent Conventions
34
35
Apply naming and organization patterns uniformly across the project.
36
37
## Quick Start
38
39
```
40
myproject/
41
├── src/
42
│ └── myproject/
43
│ ├── __init__.py
44
│ ├── services/
45
│ ├── models/
46
│ └── api/
47
├── tests/
48
├── pyproject.toml
49
└── README.md
50
```
51
52
## Fundamental Patterns
53
54
### Pattern 1: One Concept Per File
55
56
Each file should focus on a single concept or closely related set of functions. Consider splitting when a file:
57
58
- Handles multiple unrelated responsibilities
59
- Grows beyond 300-500 lines (varies by complexity)
60
- Contains classes that change for different reasons
61
62
```python
63
# Good: Focused files
64
# user_service.py - User business logic
65
# user_repository.py - User data access
66
# user_models.py - User data structures
67
68
# Avoid: Kitchen sink files
69
# user.py - Contains service, repository, models, utilities...
70
```
71
72
### Pattern 2: Explicit Public APIs with `__all__`
73
74
Define the public interface for every module. Unlisted members are internal implementation details.
75
76
```python
77
# mypackage/services/__init__.py
78
from .user_service import UserService
79
from .order_service import OrderService
80
from .exceptions import ServiceError, ValidationError
81
82
__all__ = [
83
"UserService",
84
"OrderService",
85
"ServiceError",
86
"ValidationError",
87
]
88
89
# Internal helpers remain private by omission
90
# from .internal_helpers import _validate_input # Not exported
91
```
92
93
### Pattern 3: Flat Directory Structure
94
95
Prefer minimal nesting. Deep hierarchies make imports verbose and navigation difficult.
96
97
```
98
# Preferred: Flat structure
99
project/
100
├── api/
101
│ ├── routes.py
102
│ └── middleware.py
103
├── services/
104
│ ├── user_service.py
105
│ └── order_service.py
106
├── models/
107
│ ├── user.py
108
│ └── order.py
109
└── utils/
110
└── validation.py
111
112
# Avoid: Deep nesting
113
project/core/internal/services/impl/user/
114
```
115
116
Add sub-packages only when there's a genuine sub-domain requiring isolation.
117
118
### Pattern 4: Test File Organization
119
120
Choose one approach and apply it consistently throughout the project.
121
122
**Option A: Colocated Tests**
123
124
```
125
src/
126
├── user_service.py
127
├── test_user_service.py
128
├── order_service.py
129
└── test_order_service.py
130
```
131
132
Benefits: Tests live next to the code they verify. Easy to see coverage gaps.
133
134
**Option B: Parallel Test Directory**
135
136
```
137
src/
138
├── services/
139
│ ├── user_service.py
140
│ └── order_service.py
141
tests/
142
├── services/
143
│ ├── test_user_service.py
144
│ └── test_order_service.py
145
```
146
147
Benefits: Clean separation between production and test code. Standard for larger projects.
148
149
## Advanced Patterns
150
151
### Pattern 5: Package Initialization
152
153
Use `__init__.py` to provide a clean public interface for package consumers.
154
155
```python
156
# mypackage/__init__.py
157
"""MyPackage - A library for doing useful things."""
158
159
from .core import MainClass, HelperClass
160
from .exceptions import PackageError, ConfigError
161
from .config import Settings
162
163
__all__ = [
164
"MainClass",
165
"HelperClass",
166
"PackageError",
167
"ConfigError",
168
"Settings",
169
]
170
171
__version__ = "1.0.0"
172
```
173
174
Consumers can then import directly from the package:
175
176
```python
177
from mypackage import MainClass, Settings
178
```
179
180
### Pattern 6: Layered Architecture
181
182
Organize code by architectural layer for clear separation of concerns.
183
184
```
185
myapp/
186
├── api/ # HTTP handlers, request/response
187
│ ├── routes/
188
│ └── middleware/
189
├── services/ # Business logic
190
├── repositories/ # Data access
191
├── models/ # Domain entities
192
├── schemas/ # API schemas (Pydantic)
193
└── config/ # Configuration
194
```
195
196
Each layer should only depend on layers below it, never above.
197
198
### Pattern 7: Domain-Driven Structure
199
200
For complex applications, organize by business domain rather than technical layer.
201
202
```
203
ecommerce/
204
├── users/
205
│ ├── models.py
206
│ ├── services.py
207
│ ├── repository.py
208
│ └── api.py
209
├── orders/
210
│ ├── models.py
211
│ ├── services.py
212
│ ├── repository.py
213
│ └── api.py
214
└── shared/
215
├── database.py
216
└── exceptions.py
217
```
218
219
## File and Module Naming
220
221
### Conventions
222
223
- Use `snake_case` for all file and module names: `user_repository.py`
224
- Avoid abbreviations that obscure meaning: `user_repository.py` not `usr_repo.py`
225
- Match class names to file names: `UserService` in `user_service.py`
226
227
### Import Style
228
229
Use absolute imports for clarity and reliability:
230
231
```python
232
# Preferred: Absolute imports
233
from myproject.services import UserService
234
from myproject.models import User
235
236
# Avoid: Relative imports
237
from ..services import UserService
238
from . import models
239
```
240
241
Relative imports can break when modules are moved or reorganized.
242
243
## Best Practices Summary
244
245
1. **Keep files focused** - One concept per file, consider splitting at 300-500 lines (varies by complexity)
246
2. **Define `__all__` explicitly** - Make public interfaces clear
247
3. **Prefer flat structures** - Add depth only for genuine sub-domains
248
4. **Use absolute imports** - More reliable and clearer
249
5. **Be consistent** - Apply patterns uniformly across the project
250
6. **Match names to content** - File names should describe their purpose
251
7. **Separate concerns** - Keep layers distinct and dependencies flowing one direction
252
8. **Document your structure** - Include a README explaining the organization
253