strict-module 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- strict_module/__init__.py +7 -0
- strict_module/checkers.py +806 -0
- strict_module/cli.py +152 -0
- strict_module/config/__init__.py +6 -0
- strict_module/config/_config.py +97 -0
- strict_module/config/_version.py +3 -0
- strict_module/linter.py +212 -0
- strict_module/loc_cap.py +228 -0
- strict_module/py.typed +0 -0
- strict_module/rules.py +362 -0
- strict_module-0.5.0.dist-info/METADATA +740 -0
- strict_module-0.5.0.dist-info/RECORD +15 -0
- strict_module-0.5.0.dist-info/WHEEL +4 -0
- strict_module-0.5.0.dist-info/entry_points.txt +3 -0
- strict_module-0.5.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: strict-module
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: AST-based linter for Python DTO discipline and facade-ban enforcement — framework-agnostic.
|
|
5
|
+
Project-URL: Homepage, https://pypi.org/project/strict-module/
|
|
6
|
+
Project-URL: Repository, https://github.com/jekhator/strict-module
|
|
7
|
+
Project-URL: Issues, https://github.com/jekhator/strict-module/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/jekhator/strict-module/blob/main/CHANGELOG.md
|
|
9
|
+
Author: James Ekhator
|
|
10
|
+
License: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ast,code-quality,dataclass,dto,linter,static-analysis
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: >=3.10
|
|
25
|
+
Requires-Dist: tomli>=1.1.0; python_version < '3.11'
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# strict-module
|
|
32
|
+
|
|
33
|
+
[](https://pypi.org/project/strict-module/)
|
|
34
|
+
[](https://github.com/jekhator/strict-module/actions)
|
|
35
|
+
[](https://www.python.org/downloads/)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
|
|
38
|
+
AST-based linter for Python DTO discipline and facade-ban enforcement — pluggable, framework-agnostic.
|
|
39
|
+
|
|
40
|
+
**Renamed from strict-module (v0.4.x).** The package was renamed to follow category-first naming conventions (strict- prefix). Backward-compatible fallbacks for [tool.strict-module] config and `.strict-module-baseline.json` files are included in v0.5.0+.
|
|
41
|
+
|
|
42
|
+
## Why strict-module?
|
|
43
|
+
|
|
44
|
+
Data Transfer Objects (DTOs) provide a critical boundary between services and prevent the fragmentation of business-logic definitions across codebases. However, when function signatures leak `Dict[str, Any]` or when services build dict literals inline instead of using structured DTOs, code becomes:
|
|
45
|
+
|
|
46
|
+
- **Loosely typed**: Shape mismatches only surface at runtime.
|
|
47
|
+
- **Duplicated**: The same business object gets redefined wherever it's used.
|
|
48
|
+
- **Hard to evolve**: Changing a field requires updating dicts in 10+ places.
|
|
49
|
+
|
|
50
|
+
Facade functions (module-level helpers that wrap framework machinery) similarly tend to proliferate and obscure intent when unmarked. The "facade—celery schedule" pattern makes intent explicit.
|
|
51
|
+
|
|
52
|
+
**Why in healthcare?** Healthcare systems (HIPAA/PHI/HIPAA-regulated compliance platforms) benefit from strong DTO boundaries because they force explicit thinking about what data is structured, typed, and auditable. When handling patient records, medical documents, and compliance reports, untyped dicts create liability: a field can be added silently, changed in shape unpredictably, and no type checker catches missing PII handling.
|
|
53
|
+
|
|
54
|
+
**dto-strict** enforces DTO and facade discipline via static AST analysis, with 6 focused rules:
|
|
55
|
+
|
|
56
|
+
1. **R001 (HIGH)**: Detect `Dict[str, Any]` or bare `dict`/`list`/`tuple` in service-layer function signatures (strict mode optional).
|
|
57
|
+
2. **R002 (MEDIUM)**: Flag inline dict literals with 3+ string keys; exception tags can require justification.
|
|
58
|
+
3. **R003 (MEDIUM)**: Flag `repr=False` in dataclasses (v0.2 canonical: plain `@dataclass(frozen=True, slots=True)` without `repr=False`; legacy mode available).
|
|
59
|
+
4. **R004 (HIGH)**: Demand exception tags on module-level functions (e.g., `# facade — celery schedule`).
|
|
60
|
+
5. **R005 (LOW)**: Encourage validators to use `DTO.from_dict()` pattern.
|
|
61
|
+
6. **R006 (HIGH)**: Detect `typing.Any` in function signatures (parameters and return types).
|
|
62
|
+
|
|
63
|
+
All rules are configurable; violations can be disabled, severity overridden, or paths scoped.
|
|
64
|
+
|
|
65
|
+
## Requirements
|
|
66
|
+
|
|
67
|
+
Python 3.10 or higher.
|
|
68
|
+
|
|
69
|
+
## Install
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install strict-module
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Or with pip+uvx for testing:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
uvx strict-module --help
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Quick Start
|
|
82
|
+
|
|
83
|
+
### Basic CLI Usage
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
# Lint a single file
|
|
87
|
+
strict-module apps/compliance/services.py
|
|
88
|
+
|
|
89
|
+
# Lint a directory
|
|
90
|
+
strict-module apps/
|
|
91
|
+
|
|
92
|
+
# Output as GitHub Actions annotations
|
|
93
|
+
strict-module apps/ --format github
|
|
94
|
+
|
|
95
|
+
# Output as JSON
|
|
96
|
+
strict-module apps/ --format json
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Run-Verified Example
|
|
100
|
+
|
|
101
|
+
Create a test file `example.py` with a conformant DTO:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from dataclasses import dataclass
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True, slots=True)
|
|
107
|
+
class UserDTO:
|
|
108
|
+
"""User data transfer object."""
|
|
109
|
+
user_id: int
|
|
110
|
+
email: str
|
|
111
|
+
|
|
112
|
+
def process_user(user: UserDTO) -> None:
|
|
113
|
+
"""Process a user."""
|
|
114
|
+
print(f"Processing {user.email}")
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Then lint it:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
$ strict-module example.py
|
|
121
|
+
# (no output = clean)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Now create a violating example `bad_example.py`:
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from typing import Any
|
|
128
|
+
|
|
129
|
+
def process_user(config: dict[str, Any]) -> None: # R001: Dict[str, Any] in signature
|
|
130
|
+
"""Process a user."""
|
|
131
|
+
pass
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Lint it:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
$ strict-module bad_example.py
|
|
138
|
+
bad_example.py:3: R001 Dict[str, Any] in signature: process_user
|
|
139
|
+
bad_example.py:3: R004 Module-level def without exception tag: process_user
|
|
140
|
+
bad_example.py:3: R006 typing.Any in parameter: process_user
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Configuration (pyproject.toml)
|
|
144
|
+
|
|
145
|
+
```toml
|
|
146
|
+
[tool.strict-module]
|
|
147
|
+
service_paths = [
|
|
148
|
+
"apps/*/services/*.py",
|
|
149
|
+
"**/services/*.py",
|
|
150
|
+
]
|
|
151
|
+
dto_paths = [
|
|
152
|
+
"**/dtos.py",
|
|
153
|
+
"**/dtos/*.py",
|
|
154
|
+
]
|
|
155
|
+
exception_tags = [
|
|
156
|
+
"facade — celery schedule",
|
|
157
|
+
"FRAMEWORK",
|
|
158
|
+
]
|
|
159
|
+
disabled_rules = ["R005"] # Disable low-priority rules if desired
|
|
160
|
+
severity_overrides = { "R002" = "low" } # Downgrade specific rules
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Strict Mode (v0.2)
|
|
164
|
+
|
|
165
|
+
v0.2 introduces **canonical mode** alignment with modern DTO practices and strict collection detection:
|
|
166
|
+
|
|
167
|
+
```toml
|
|
168
|
+
[tool.strict-module]
|
|
169
|
+
|
|
170
|
+
# R001: Catch bare dict/list/tuple without type parameters
|
|
171
|
+
strict_collections = true # Default: false. When true, bare collections trigger violations.
|
|
172
|
+
|
|
173
|
+
# R002: Require justification on exception tags + configurable dict key threshold
|
|
174
|
+
exception_tag_requires_justification = true # Default: false.
|
|
175
|
+
# Tags must now use format: "tag: explanation" (e.g., "facade — celery schedule: transient event payload")
|
|
176
|
+
|
|
177
|
+
min_dict_keys = 3 # NEW in v0.2: Threshold for R002 dict literal flagging (default: 3)
|
|
178
|
+
|
|
179
|
+
# Limit reuse of exception tags in a single file
|
|
180
|
+
max_exception_tags_per_file = 3 # Default: null (no limit)
|
|
181
|
+
|
|
182
|
+
# R003: Canonical mode (v0.2 default) flags repr=False as anti-canonical + strict/relaxed modes
|
|
183
|
+
r003_mode = "canonical" # Default: "canonical" (v0.2). Use "legacy" for v0.1 behavior.
|
|
184
|
+
# In canonical mode: @dataclass(frozen=True, slots=True) is correct; repr=False is flagged.
|
|
185
|
+
# In legacy mode: @dataclass must include frozen=True, slots=True, AND repr=False (v0.1 requirement).
|
|
186
|
+
|
|
187
|
+
r003_strict_repr = true # NEW in v0.2: In canonical mode, flag repr=False (default: true)
|
|
188
|
+
# Set to false for relaxed mode: only checks frozen+slots, ignores repr=False
|
|
189
|
+
|
|
190
|
+
# R004: NEW auto-detect class-method-wrapping pattern
|
|
191
|
+
# Module-level functions that delegate to class methods are now auto-detected
|
|
192
|
+
# (no exception tag needed; reduces false positives)
|
|
193
|
+
|
|
194
|
+
# R006: Scope typing.Any detection to specific paths
|
|
195
|
+
r006_paths = [
|
|
196
|
+
"apps/*/services/*.py",
|
|
197
|
+
"**/services/*.py",
|
|
198
|
+
]
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### Baseline Ratchet Mode (v0.2)
|
|
202
|
+
|
|
203
|
+
Accept current violations as "baseline" debt and track only new violations:
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
# Generate baseline from current state
|
|
207
|
+
strict-module apps/ --generate-baseline > .strict-module-baseline.json
|
|
208
|
+
|
|
209
|
+
# Subsequent runs accept baseline violations; new ones trigger failure
|
|
210
|
+
strict-module apps/ --baseline .strict-module-baseline.json
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Baseline tracks violations by file, line, and rule ID. When violations are fixed and removed from the codebase, the baseline can be regenerated (exit code 0 + notice on removal).
|
|
214
|
+
|
|
215
|
+
### LOC Cap Enforcement (`strict-module loc-cap`)
|
|
216
|
+
|
|
217
|
+
The `loc-cap` subcommand enforces per-file line-of-code limits with configurable hard/soft caps and baseline ratcheting (v0.3+). Test files are automatically exempt from the cap.
|
|
218
|
+
|
|
219
|
+
**Test file exemption:** Files matching any of the following patterns are skipped from LOC cap enforcement:
|
|
220
|
+
- Basename is `conftest.py`
|
|
221
|
+
- Basename matches `test_*.py`
|
|
222
|
+
- File is under a `tests/` directory
|
|
223
|
+
|
|
224
|
+
Example: a 500-line test file will not trigger hard-cap violations, allowing test fixtures and comprehensive test suites to grow freely.
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
# Run LOC cap check
|
|
228
|
+
strict-module loc-cap src/ --hard-cap 694 --soft-target 500
|
|
229
|
+
|
|
230
|
+
# Generate baseline (records baseline LOC for all files)
|
|
231
|
+
strict-module loc-cap src/ --generate-baseline > .loc-cap-baseline.txt
|
|
232
|
+
|
|
233
|
+
# Check with ratchet enforcement (new files over hard cap fail, baselined files cannot grow)
|
|
234
|
+
strict-module loc-cap src/ --baseline .loc-cap-baseline.txt
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
**Why canonical mode?** Per 2026-05-09 DTO-strict pivot, the canonical pattern is:
|
|
238
|
+
- `@dataclass(frozen=True, slots=True)` — immutability + memory efficiency
|
|
239
|
+
- **NO `repr=False`** — let repr work normally; custom `__repr__` not needed
|
|
240
|
+
- Store values, don't override output; if a field is PII-sensitive, use external redaction tools
|
|
241
|
+
|
|
242
|
+
### GitHub Actions
|
|
243
|
+
|
|
244
|
+
Create `.github/workflows/strict-module.yml`:
|
|
245
|
+
|
|
246
|
+
```yaml
|
|
247
|
+
name: strict-module
|
|
248
|
+
on:
|
|
249
|
+
pull_request:
|
|
250
|
+
paths: ['apps/**.py']
|
|
251
|
+
|
|
252
|
+
jobs:
|
|
253
|
+
lint:
|
|
254
|
+
runs-on: ubuntu-latest
|
|
255
|
+
steps:
|
|
256
|
+
- uses: actions/checkout@v4
|
|
257
|
+
- uses: actions/setup-python@v5
|
|
258
|
+
with:
|
|
259
|
+
python-version: '3.12'
|
|
260
|
+
- run: pip install strict-module
|
|
261
|
+
- run: strict-module apps/ --format github
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
### Pre-commit Hook
|
|
265
|
+
|
|
266
|
+
Add to `.pre-commit-config.yaml`:
|
|
267
|
+
|
|
268
|
+
```yaml
|
|
269
|
+
- repo: local
|
|
270
|
+
hooks:
|
|
271
|
+
- id: strict-module
|
|
272
|
+
name: strict-module
|
|
273
|
+
entry: strict-module
|
|
274
|
+
language: python
|
|
275
|
+
types: [python]
|
|
276
|
+
additional_dependencies: ['strict-module']
|
|
277
|
+
stages: [commit]
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
## Rules
|
|
281
|
+
|
|
282
|
+
### R001: Dict[str, Any] and Bare Collections in Service Signatures (HIGH)
|
|
283
|
+
|
|
284
|
+
Service-layer functions should not accept or return `Dict[str, Any]`. With `strict_collections=true`, bare `dict`, `list`, and `tuple` without type parameters are also flagged.
|
|
285
|
+
|
|
286
|
+
**Fail (always):**
|
|
287
|
+
```python
|
|
288
|
+
def process_user(config: Dict[str, Any]) -> Dict[str, Any]:
|
|
289
|
+
return {"status": "ok"}
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
**Fail (with strict_collections=true):**
|
|
293
|
+
```python
|
|
294
|
+
def fetch_users() -> list: # Bare list
|
|
295
|
+
return []
|
|
296
|
+
|
|
297
|
+
def merge_configs(base: dict, overrides: dict) -> dict: # Bare dicts
|
|
298
|
+
return {**base, **overrides}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
**Pass:**
|
|
302
|
+
```python
|
|
303
|
+
from typing import Dict
|
|
304
|
+
|
|
305
|
+
@dataclass(frozen=True, slots=True)
|
|
306
|
+
class UserConfigDTO:
|
|
307
|
+
timeout: int
|
|
308
|
+
retries: int
|
|
309
|
+
|
|
310
|
+
def process_user(config: UserConfigDTO) -> Dict[str, str]:
|
|
311
|
+
return {"status": "ok"}
|
|
312
|
+
|
|
313
|
+
def fetch_users() -> list[UserDTO]: # Typed list
|
|
314
|
+
return []
|
|
315
|
+
|
|
316
|
+
def merge_configs(base: dict[str, Any], overrides: dict[str, Any]) -> dict[str, Any]: # Typed dicts
|
|
317
|
+
return {**base, **overrides}
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
**Rationale:** Typed parameters enable IDE completion and catch shape mismatches early. Bare collections hide shape from static checkers and readers.
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
### R002: Inline Dict Literals (MEDIUM)
|
|
325
|
+
|
|
326
|
+
Service files with inline dict literals containing 3+ string keys should define a DTO instead. Exception tags allow one-off inline dicts; with `exception_tag_requires_justification=true`, tags must include a colon-delimited explanation.
|
|
327
|
+
|
|
328
|
+
**Exemption:** Dict literals returned from `to_*` serializer methods in `@dataclass`-decorated classes are automatically exempt. These are serialized outputs, not unconverted business shapes. Example:
|
|
329
|
+
|
|
330
|
+
```python
|
|
331
|
+
@dataclass(frozen=True, slots=True)
|
|
332
|
+
class UserDTO:
|
|
333
|
+
user_id: int
|
|
334
|
+
status: str
|
|
335
|
+
timestamp: str
|
|
336
|
+
|
|
337
|
+
def to_dict(self) -> dict: # Exempt from R002
|
|
338
|
+
return {
|
|
339
|
+
"user_id": self.user_id,
|
|
340
|
+
"status": self.status,
|
|
341
|
+
"timestamp": self.timestamp,
|
|
342
|
+
}
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
**Fail (no tag):**
|
|
346
|
+
```python
|
|
347
|
+
def build_response(user_id: int) -> dict:
|
|
348
|
+
return {
|
|
349
|
+
"user_id": user_id,
|
|
350
|
+
"status": "active",
|
|
351
|
+
"timestamp": "2025-01-01",
|
|
352
|
+
}
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
**Fail (tag without justification, if required):**
|
|
356
|
+
```python
|
|
357
|
+
def build_response(user_id: int) -> dict: # facade — celery schedule
|
|
358
|
+
return {
|
|
359
|
+
"user_id": user_id,
|
|
360
|
+
"status": "active",
|
|
361
|
+
"timestamp": "2025-01-01",
|
|
362
|
+
}
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
**Pass (with justified tag):**
|
|
366
|
+
```python
|
|
367
|
+
def build_response(user_id: int) -> dict: # facade — celery schedule: SNS event envelope (transient)
|
|
368
|
+
return {
|
|
369
|
+
"user_id": user_id,
|
|
370
|
+
"status": "active",
|
|
371
|
+
"timestamp": "2025-01-01",
|
|
372
|
+
}
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
**Pass (define DTO instead):**
|
|
376
|
+
```python
|
|
377
|
+
@dataclass(frozen=True, slots=True)
|
|
378
|
+
class ResponseDTO:
|
|
379
|
+
user_id: int
|
|
380
|
+
status: str
|
|
381
|
+
timestamp: str
|
|
382
|
+
|
|
383
|
+
def build_response(user_id: int) -> ResponseDTO:
|
|
384
|
+
return ResponseDTO(user_id, "active", "2025-01-01")
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
**Rationale:** Shared shapes should live in DTOs. Inline dicts make duplication invisible. Exception tags are for rare transient payloads; they should explain why.
|
|
388
|
+
|
|
389
|
+
---
|
|
390
|
+
|
|
391
|
+
### R003: Dataclass Canonical Form (MEDIUM)
|
|
392
|
+
|
|
393
|
+
**Canonical mode (v0.2 default):** Dataclasses must use `frozen=True, slots=True` WITHOUT `repr=False`.
|
|
394
|
+
|
|
395
|
+
**Legacy mode (v0.1):** Requires `frozen=True, slots=True, repr=False`.
|
|
396
|
+
|
|
397
|
+
#### Canonical Mode (v0.2)
|
|
398
|
+
|
|
399
|
+
**Fail (canonical mode):**
|
|
400
|
+
```python
|
|
401
|
+
@dataclass(frozen=True, slots=True, repr=False) # Anti-canonical: has repr=False
|
|
402
|
+
class UserDTO:
|
|
403
|
+
user_id: int
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
**Pass (canonical mode):**
|
|
407
|
+
```python
|
|
408
|
+
@dataclass(frozen=True, slots=True)
|
|
409
|
+
class UserDTO:
|
|
410
|
+
user_id: int
|
|
411
|
+
|
|
412
|
+
@dataclass(frozen=True, slots=True) # Both params present
|
|
413
|
+
class ConfigDTO:
|
|
414
|
+
timeout: int
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
**Rationale (canonical):**
|
|
418
|
+
- `frozen=True`: Immutability enforces single-source-of-truth.
|
|
419
|
+
- `slots=True`: Memory efficiency and prevents attribute typos.
|
|
420
|
+
- **NO `repr=False`**: Default repr is fine; if a field is sensitive, use external redaction (logging mixin, etc.)
|
|
421
|
+
|
|
422
|
+
#### Legacy Mode (v0.1)
|
|
423
|
+
|
|
424
|
+
Use `r003_mode = "legacy"` in `pyproject.toml` if your codebase still requires `repr=False`:
|
|
425
|
+
|
|
426
|
+
```python
|
|
427
|
+
@dataclass(frozen=True, slots=True, repr=False)
|
|
428
|
+
class UserDTO:
|
|
429
|
+
user_id: int
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
---
|
|
433
|
+
|
|
434
|
+
### R004: Module-Level Functions (HIGH)
|
|
435
|
+
|
|
436
|
+
Bare module-level functions (facades, framework hooks) must carry an exception tag in a comment or docstring.
|
|
437
|
+
|
|
438
|
+
**Fail:**
|
|
439
|
+
```python
|
|
440
|
+
def process_user(user_id: int):
|
|
441
|
+
pass
|
|
442
|
+
|
|
443
|
+
def send_notification(message: str):
|
|
444
|
+
pass
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
**Pass:**
|
|
448
|
+
```python
|
|
449
|
+
def process_user(user_id: int): # facade — celery schedule
|
|
450
|
+
pass
|
|
451
|
+
|
|
452
|
+
def send_notification(message: str): # FRAMEWORK
|
|
453
|
+
"""Send via SNS."""
|
|
454
|
+
pass
|
|
455
|
+
|
|
456
|
+
class UserService:
|
|
457
|
+
def process(self, user_id: int):
|
|
458
|
+
# Class methods don't need tags
|
|
459
|
+
pass
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
**Exception Tags:** Configurable via `pyproject.toml` `exception_tags` list.
|
|
463
|
+
|
|
464
|
+
**Rationale:** Facades blur intent. Tags make intent explicit and signal "this is framework-specific, not business logic."
|
|
465
|
+
|
|
466
|
+
---
|
|
467
|
+
|
|
468
|
+
### R005: Validator Pattern (LOW)
|
|
469
|
+
|
|
470
|
+
`validate_*()` functions should use `DTO.from_dict()` or raise `ValidationError` to enforce payload shape.
|
|
471
|
+
|
|
472
|
+
**Fail:**
|
|
473
|
+
```python
|
|
474
|
+
def validate_user_payload(payload: dict) -> bool:
|
|
475
|
+
return "user_id" in payload and "email" in payload
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
**Pass:**
|
|
479
|
+
```python
|
|
480
|
+
def validate_user_payload(payload: dict) -> UserDTO:
|
|
481
|
+
try:
|
|
482
|
+
user = UserDTO(
|
|
483
|
+
user_id=payload["user_id"],
|
|
484
|
+
email=payload["email"],
|
|
485
|
+
)
|
|
486
|
+
return user
|
|
487
|
+
except (KeyError, TypeError) as e:
|
|
488
|
+
raise ValidationError(f"Invalid shape: {e}")
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
**Rationale:** Validators should enforce structure, not just presence.
|
|
492
|
+
|
|
493
|
+
---
|
|
494
|
+
|
|
495
|
+
### R006: typing.Any in Signatures (HIGH)
|
|
496
|
+
|
|
497
|
+
Function signatures in service files should not use `typing.Any`. Build a proper DTO or use narrow type protocols instead.
|
|
498
|
+
|
|
499
|
+
**Fail:**
|
|
500
|
+
```python
|
|
501
|
+
from typing import Any
|
|
502
|
+
|
|
503
|
+
def process(data: Any) -> Any: # Bad: loses all type info
|
|
504
|
+
pass
|
|
505
|
+
|
|
506
|
+
def fetch_config() -> Optional[Any]: # Bad: Any defeats Optional
|
|
507
|
+
return None
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
**Pass:**
|
|
511
|
+
```python
|
|
512
|
+
from typing import Optional, Protocol
|
|
513
|
+
|
|
514
|
+
class Readable(Protocol):
|
|
515
|
+
def read(self) -> bytes:
|
|
516
|
+
...
|
|
517
|
+
|
|
518
|
+
def process(data: dict[str, str]) -> dict[str, int]: # Properly typed
|
|
519
|
+
pass
|
|
520
|
+
|
|
521
|
+
def fetch_config() -> Optional[ConfigDTO]: # Specific type
|
|
522
|
+
return None
|
|
523
|
+
|
|
524
|
+
def read_file(f: Readable) -> bytes: # Protocol for file-like objects
|
|
525
|
+
return f.read()
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
**Rationale:** `Any` defeats static type checking and IDE completion. It hides shape assumptions and makes refactoring dangerous. Use protocols for file-like or callback types; use DTOs for business shapes.
|
|
529
|
+
|
|
530
|
+
---
|
|
531
|
+
|
|
532
|
+
## PHI / Sensitive Data Handling (Pattern 1)
|
|
533
|
+
|
|
534
|
+
**Why R003 removed blanket `repr=False`:** The v0.2 canonical pivot intentionally moves away from blanket `repr=False` as a PHI masking mechanism. Instead, use **explicit `__repr__` overrides** on DTOs containing sensitive fields.
|
|
535
|
+
|
|
536
|
+
**Pattern 1: Explicit `__repr__` on Sensitive DTOs**
|
|
537
|
+
|
|
538
|
+
```python
|
|
539
|
+
from dataclasses import dataclass
|
|
540
|
+
|
|
541
|
+
@dataclass(frozen=True, slots=True)
|
|
542
|
+
class Patient:
|
|
543
|
+
"""Patient DTO with sensitive fields."""
|
|
544
|
+
patient_id: str
|
|
545
|
+
name: str
|
|
546
|
+
ssn: str # Sensitive
|
|
547
|
+
date_of_birth: str # Sensitive
|
|
548
|
+
|
|
549
|
+
def __repr__(self) -> str:
|
|
550
|
+
"""Mask PHI fields in repr."""
|
|
551
|
+
return f"Patient(patient_id={self.patient_id!r}, name=<redacted>, ssn=<redacted>, date_of_birth=<redacted>)"
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
When a Patient DTO is logged or printed, only non-sensitive fields appear:
|
|
555
|
+
```python
|
|
556
|
+
>>> p = Patient(patient_id="P123", name="Alice", ssn="123-45-6789", date_of_birth="1990-01-01")
|
|
557
|
+
>>> print(p)
|
|
558
|
+
Patient(patient_id='P123', name=<redacted>, ssn=<redacted>, date_of_birth=<redacted>)
|
|
559
|
+
```
|
|
560
|
+
|
|
561
|
+
**Why explicit over blanket?**
|
|
562
|
+
- **Auditable:** Developers explicitly decide which fields are sensitive and how to mask them.
|
|
563
|
+
- **Flexible:** Different DTOs can have different masking strategies (redact, hash, truncate, etc.).
|
|
564
|
+
- **Future-proof:** External tools (e.g., AWS Comprehend Medical) can be layered on top for dynamic PHI detection.
|
|
565
|
+
- **Healthcare / HIPAA:** The combination of explicit DTOs + selective `__repr__` overrides is a standard privacy-by-design pattern in regulated systems.
|
|
566
|
+
|
|
567
|
+
---
|
|
568
|
+
|
|
569
|
+
## Suppressing Violations
|
|
570
|
+
|
|
571
|
+
Violations can be suppressed using `# noqa` comments. The linter recognizes:
|
|
572
|
+
|
|
573
|
+
- **`# noqa`** — Suppress all rules on this line
|
|
574
|
+
- **`# noqa: dto-strict`** — Suppress all strict-module rules on this line
|
|
575
|
+
- **`# noqa: dto-strict-R001`** — Suppress rule R001 only
|
|
576
|
+
- **`# noqa: dto-strict-R001, dto-strict-R002`** — Suppress multiple rules
|
|
577
|
+
|
|
578
|
+
**Examples:**
|
|
579
|
+
|
|
580
|
+
```python
|
|
581
|
+
# Suppress a Dict[str, Any] violation on a specific function
|
|
582
|
+
def legacy_callback(config: Dict[str, Any]) -> None: # noqa: dto-strict-R001
|
|
583
|
+
"""Old API we can't change."""
|
|
584
|
+
pass
|
|
585
|
+
|
|
586
|
+
# Suppress all rules on a line
|
|
587
|
+
def process() -> dict: # noqa
|
|
588
|
+
return {}
|
|
589
|
+
|
|
590
|
+
# Suppress just R002 (inline dict literal) violation
|
|
591
|
+
error_response = { # noqa: dto-strict-R002
|
|
592
|
+
"status": "error",
|
|
593
|
+
"code": 500,
|
|
594
|
+
"message": "Internal server error",
|
|
595
|
+
}
|
|
596
|
+
```
|
|
597
|
+
|
|
598
|
+
---
|
|
599
|
+
|
|
600
|
+
## Output Formats
|
|
601
|
+
|
|
602
|
+
### Text (default)
|
|
603
|
+
|
|
604
|
+
```
|
|
605
|
+
app.py:10: R001 Dict[str, Any] in signature: process_user
|
|
606
|
+
service.py:20: R002 Inline dict literal with 4 keys
|
|
607
|
+
```
|
|
608
|
+
|
|
609
|
+
### GitHub Actions
|
|
610
|
+
|
|
611
|
+
```
|
|
612
|
+
::error file=app.py,line=10,col=5::R001 Dict[str, Any] in signature: process_user
|
|
613
|
+
::warning file=service.py,line=20,col=0::R002 Inline dict literal with 4 keys
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
### JSON
|
|
617
|
+
|
|
618
|
+
```json
|
|
619
|
+
[
|
|
620
|
+
{
|
|
621
|
+
"rule_id": "R001",
|
|
622
|
+
"severity": "HIGH",
|
|
623
|
+
"file": "app.py",
|
|
624
|
+
"line": 10,
|
|
625
|
+
"col": 5,
|
|
626
|
+
"message": "Dict[str, Any] in signature: process_user"
|
|
627
|
+
}
|
|
628
|
+
]
|
|
629
|
+
```
|
|
630
|
+
|
|
631
|
+
## Exit Codes
|
|
632
|
+
|
|
633
|
+
| Code | Meaning |
|
|
634
|
+
|------|---------|
|
|
635
|
+
| 0 | No violations |
|
|
636
|
+
| 1 | HIGH severity violations present |
|
|
637
|
+
| 2 | MEDIUM severity violations only |
|
|
638
|
+
| 3 | LOW severity violations only |
|
|
639
|
+
|
|
640
|
+
## Configuration Reference
|
|
641
|
+
|
|
642
|
+
```toml
|
|
643
|
+
[tool.strict-module]
|
|
644
|
+
|
|
645
|
+
# Paths to check for service-layer violations (R001, R002, R004, R006)
|
|
646
|
+
# Default: ["apps/*/services/*.py", "**/services/*.py"]
|
|
647
|
+
service_paths = [
|
|
648
|
+
"apps/*/services/*.py",
|
|
649
|
+
"**/services/*.py",
|
|
650
|
+
]
|
|
651
|
+
|
|
652
|
+
# Paths to check for DTO definitions (R003)
|
|
653
|
+
# Default: ["**/dtos.py", "**/dtos/*.py"]
|
|
654
|
+
dto_paths = [
|
|
655
|
+
"**/dtos.py",
|
|
656
|
+
"**/dtos/*.py",
|
|
657
|
+
]
|
|
658
|
+
|
|
659
|
+
# Paths for R006 (typing.Any detection)
|
|
660
|
+
# Default: ["apps/*/services/*.py", "**/services/*.py"]
|
|
661
|
+
r006_paths = [
|
|
662
|
+
"apps/*/services/*.py",
|
|
663
|
+
"**/services/*.py",
|
|
664
|
+
]
|
|
665
|
+
|
|
666
|
+
# Allowed exception tags for R004 (module-level facades)
|
|
667
|
+
# Default: ["facade — celery schedule", "FRAMEWORK"]
|
|
668
|
+
exception_tags = [
|
|
669
|
+
"facade — celery schedule",
|
|
670
|
+
"FRAMEWORK",
|
|
671
|
+
"CUSTOM_TAG",
|
|
672
|
+
]
|
|
673
|
+
|
|
674
|
+
# (v0.2) Bare dict/list/tuple without type parameters flagged as violations
|
|
675
|
+
# Default: false
|
|
676
|
+
strict_collections = true
|
|
677
|
+
|
|
678
|
+
# (v0.2) Exception tags must include colon-delimited justification
|
|
679
|
+
# Default: false
|
|
680
|
+
exception_tag_requires_justification = true
|
|
681
|
+
|
|
682
|
+
# (v0.2) Maximum exception tags per file (null = unlimited)
|
|
683
|
+
# Default: null
|
|
684
|
+
max_exception_tags_per_file = 3
|
|
685
|
+
|
|
686
|
+
# (v0.2) R003 mode: "canonical" (v0.2 default) or "legacy" (v0.1)
|
|
687
|
+
# In canonical: repr=False is anti-canonical and flagged
|
|
688
|
+
# In legacy: frozen=True, slots=True, repr=False all required
|
|
689
|
+
# Default: "canonical"
|
|
690
|
+
r003_mode = "canonical"
|
|
691
|
+
|
|
692
|
+
# Disable specific rules entirely
|
|
693
|
+
# Default: []
|
|
694
|
+
disabled_rules = ["R005"]
|
|
695
|
+
|
|
696
|
+
# Override severity for specific rules
|
|
697
|
+
# Valid values: "HIGH", "MEDIUM", "LOW"
|
|
698
|
+
# Default: {}
|
|
699
|
+
severity_overrides = {
|
|
700
|
+
"R002" = "low",
|
|
701
|
+
}
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
## Design Philosophy
|
|
705
|
+
|
|
706
|
+
**Pluggable, not opinionated.** Every rule is:
|
|
707
|
+
|
|
708
|
+
- **Configurable**: Path patterns, exception tags, severity levels.
|
|
709
|
+
- **Disable-able**: Set `disabled_rules = ["R001"]` to skip it entirely.
|
|
710
|
+
- **Framework-agnostic**: No Django/FastAPI/Flask assumptions; adapters for each framework are opt-in extras.
|
|
711
|
+
|
|
712
|
+
**Defaults bundled, not imposed.** Out-of-the-box rules target Django + DRF + Celery patterns, but you can customize for your stack.
|
|
713
|
+
|
|
714
|
+
## Development
|
|
715
|
+
|
|
716
|
+
```bash
|
|
717
|
+
git clone https://github.com/jekhator/strict-module.git
|
|
718
|
+
cd strict-module
|
|
719
|
+
python3.12 -m venv .venv && source .venv/bin/activate
|
|
720
|
+
pip install -e ".[dev]"
|
|
721
|
+
|
|
722
|
+
# Run tests
|
|
723
|
+
python3.12 -m pytest tests/ -v
|
|
724
|
+
|
|
725
|
+
# Run linter on itself
|
|
726
|
+
strict-module strict_module/ --format github
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
## License
|
|
730
|
+
|
|
731
|
+
Apache License 2.0. See LICENSE.
|
|
732
|
+
|
|
733
|
+
## Contributing
|
|
734
|
+
|
|
735
|
+
Issues and PRs welcome. Please include fixtures (good + bad examples) for new rules.
|
|
736
|
+
|
|
737
|
+
## See Also
|
|
738
|
+
|
|
739
|
+
- [pii-aware-mixin](https://github.com/jekhator/pii-aware-mixin) — Auto-hide PII in dataclass repr/logging.
|
|
740
|
+
- [logging-mixin](https://github.com/jekhator/logging-mixin) — Class-bound structured logging with correlation IDs.
|