@sylix/coworker 2.0.11 → 2.0.12
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.
- package/dist/commands/slash/config.d.ts.map +1 -1
- package/dist/commands/slash/config.js +22 -4
- package/dist/commands/slash/config.js.map +1 -1
- package/dist/core/CoWorkerAgent.d.ts.map +1 -1
- package/dist/core/CoWorkerAgent.js +6 -3
- package/dist/core/CoWorkerAgent.js.map +1 -1
- package/dist/skills/defaults/accessibility/screen-reader-testing.md +545 -0
- package/dist/skills/defaults/accessibility/wcag-audit-patterns.md +555 -0
- package/dist/skills/defaults/ai-ml/rag.md +276 -0
- package/dist/skills/defaults/backend-development/api-design-principles.md +528 -0
- package/dist/skills/defaults/backend-development/api-design.md +285 -0
- package/dist/skills/defaults/backend-development/architecture-patterns.md +494 -0
- package/dist/skills/defaults/backend-development/async-python.md +237 -0
- package/dist/skills/defaults/backend-development/auth-implementation-patterns.md +638 -0
- package/dist/skills/defaults/backend-development/bazel-build-optimization.md +387 -0
- package/dist/skills/defaults/backend-development/billing-automation/SKILL.md +566 -0
- package/dist/skills/defaults/backend-development/code-review-excellence.md +538 -0
- package/dist/skills/defaults/backend-development/cqrs-implementation.md +554 -0
- package/dist/skills/defaults/backend-development/database-design.md +305 -0
- package/dist/skills/defaults/backend-development/debugging-strategies.md +536 -0
- package/dist/skills/defaults/backend-development/e2e-testing-patterns.md +544 -0
- package/dist/skills/defaults/backend-development/error-handling-patterns.md +641 -0
- package/dist/skills/defaults/backend-development/fastapi-templates.md +559 -0
- package/dist/skills/defaults/backend-development/fastapi.md +309 -0
- package/dist/skills/defaults/backend-development/git-advanced-workflows.md +405 -0
- package/dist/skills/defaults/backend-development/microservices-patterns.md +595 -0
- package/dist/skills/defaults/backend-development/microservices.md +284 -0
- package/dist/skills/defaults/backend-development/monorepo-management.md +623 -0
- package/dist/skills/defaults/backend-development/nodejs-backend-patterns.md +1048 -0
- package/dist/skills/defaults/backend-development/nx-workspace-patterns.md +457 -0
- package/dist/skills/defaults/backend-development/paypal-integration/SKILL.md +478 -0
- package/dist/skills/defaults/backend-development/pci-compliance/SKILL.md +480 -0
- package/dist/skills/defaults/backend-development/python-anti-patterns.md +349 -0
- package/dist/skills/defaults/backend-development/python-background-jobs.md +364 -0
- package/dist/skills/defaults/backend-development/python-code-style.md +360 -0
- package/dist/skills/defaults/backend-development/python-configuration.md +368 -0
- package/dist/skills/defaults/backend-development/python-design-patterns.md +296 -0
- package/dist/skills/defaults/backend-development/python-error-handling.md +323 -0
- package/dist/skills/defaults/backend-development/python-packaging.md +887 -0
- package/dist/skills/defaults/backend-development/python-performance-optimization.md +874 -0
- package/dist/skills/defaults/backend-development/python-project-structure.md +252 -0
- package/dist/skills/defaults/backend-development/python-resilience.md +376 -0
- package/dist/skills/defaults/backend-development/python-resource-management.md +421 -0
- package/dist/skills/defaults/backend-development/python-type-safety.md +428 -0
- package/dist/skills/defaults/backend-development/sql-optimization-patterns.md +509 -0
- package/dist/skills/defaults/backend-development/stripe-integration/SKILL.md +522 -0
- package/dist/skills/defaults/backend-development/turborepo-caching.md +376 -0
- package/dist/skills/defaults/blockchain/defi-protocol-templates.md +430 -0
- package/dist/skills/defaults/blockchain/nft-standards.md +364 -0
- package/dist/skills/defaults/blockchain/solidity-security.md +514 -0
- package/dist/skills/defaults/blockchain/web3-testing.md +360 -0
- package/dist/skills/defaults/business/competitive-landscape/SKILL.md +527 -0
- package/dist/skills/defaults/business/market-sizing-analysis/SKILL.md +451 -0
- package/dist/skills/defaults/business/startup-financial-modeling/SKILL.md +494 -0
- package/dist/skills/defaults/business/startup-metrics-framework/SKILL.md +564 -0
- package/dist/skills/defaults/business/team-composition-analysis.md +437 -0
- package/dist/skills/defaults/compliance/employment-contract-templates/SKILL.md +527 -0
- package/dist/skills/defaults/compliance/gdpr-data-handling/SKILL.md +630 -0
- package/dist/skills/defaults/data-engineering/airflow-dag-patterns.md +436 -0
- package/dist/skills/defaults/data-engineering/airflow.md +519 -0
- package/dist/skills/defaults/data-engineering/data-quality.md +583 -0
- package/dist/skills/defaults/data-engineering/dbt-transformation-patterns.md +482 -0
- package/dist/skills/defaults/data-engineering/dbt.md +556 -0
- package/dist/skills/defaults/data-engineering/ml-pipeline-workflow/SKILL.md +247 -0
- package/dist/skills/defaults/data-engineering/spark-optimization.md +348 -0
- package/dist/skills/defaults/data-engineering/spark.md +411 -0
- package/dist/skills/defaults/database/postgresql.md +202 -0
- package/dist/skills/defaults/debugging/systematic-debugging.md +249 -0
- package/dist/skills/defaults/devops/architecture-decision-records.md +448 -0
- package/dist/skills/defaults/devops/changelog-automation.md +580 -0
- package/dist/skills/defaults/devops/cicd.md +314 -0
- package/dist/skills/defaults/devops/cloud.md +263 -0
- package/dist/skills/defaults/devops/code-review-excellence.md +299 -0
- package/dist/skills/defaults/devops/cost-optimization.md +295 -0
- package/dist/skills/defaults/devops/deployment-pipeline-design.md +356 -0
- package/dist/skills/defaults/devops/docker.md +281 -0
- package/dist/skills/defaults/devops/git-workflows.md +205 -0
- package/dist/skills/defaults/devops/github-actions.md +311 -0
- package/dist/skills/defaults/devops/gitlab-ci-patterns.md +266 -0
- package/dist/skills/defaults/devops/hybrid-cloud-networking.md +241 -0
- package/dist/skills/defaults/devops/istio-traffic-management.md +327 -0
- package/dist/skills/defaults/devops/kubernetes.md +339 -0
- package/dist/skills/defaults/devops/linkerd-patterns.md +311 -0
- package/dist/skills/defaults/devops/multi-cloud-architecture.md +181 -0
- package/dist/skills/defaults/devops/observability.md +243 -0
- package/dist/skills/defaults/devops/openapi-spec-generation.md +1024 -0
- package/dist/skills/defaults/devops/postmortem-writing.md +396 -0
- package/dist/skills/defaults/devops/prometheus-configuration.md +265 -0
- package/dist/skills/defaults/devops/secrets-management.md +341 -0
- package/dist/skills/defaults/devops/service-mesh-observability.md +385 -0
- package/dist/skills/defaults/devops/terraform-module-library.md +244 -0
- package/dist/skills/defaults/finance/backtesting-frameworks/SKILL.md +663 -0
- package/dist/skills/defaults/finance/risk-metrics-calculation/SKILL.md +557 -0
- package/dist/skills/defaults/frontend/accessibility-compliance.md +420 -0
- package/dist/skills/defaults/frontend/design-system-patterns.md +337 -0
- package/dist/skills/defaults/frontend/interaction-design.md +327 -0
- package/dist/skills/defaults/frontend/javascript.md +311 -0
- package/dist/skills/defaults/frontend/modern-javascript-patterns.md +927 -0
- package/dist/skills/defaults/frontend/react-native-design.md +440 -0
- package/dist/skills/defaults/frontend/react.md +345 -0
- package/dist/skills/defaults/frontend/responsive-design.md +472 -0
- package/dist/skills/defaults/frontend/tailwind-design-system.md +337 -0
- package/dist/skills/defaults/frontend/typescript-advanced-types.md +724 -0
- package/dist/skills/defaults/frontend/typescript.md +334 -0
- package/dist/skills/defaults/frontend/visual-design-foundations.md +326 -0
- package/dist/skills/defaults/frontend/web-component-design.md +279 -0
- package/dist/skills/defaults/game-development/godot-gdscript-patterns.md +188 -0
- package/dist/skills/defaults/game-development/unity-ecs-patterns.md +594 -0
- package/dist/skills/defaults/kubernetes/gitops-workflow.md +285 -0
- package/dist/skills/defaults/kubernetes/gitops.md +280 -0
- package/dist/skills/defaults/kubernetes/helm-chart-scaffolding.md +553 -0
- package/dist/skills/defaults/kubernetes/helm.md +343 -0
- package/dist/skills/defaults/kubernetes/k8s-manifest-generator.md +501 -0
- package/dist/skills/defaults/kubernetes/k8s-security-policies.md +342 -0
- package/dist/skills/defaults/kubernetes/manifests.md +330 -0
- package/dist/skills/defaults/kubernetes/security.md +337 -0
- package/dist/skills/defaults/llm-application/embedding-strategies.md +608 -0
- package/dist/skills/defaults/llm-application/hybrid-search-implementation.md +570 -0
- package/dist/skills/defaults/llm-application/hybrid-search.md +570 -0
- package/dist/skills/defaults/llm-application/langchain-architecture.md +666 -0
- package/dist/skills/defaults/llm-application/langchain.md +259 -0
- package/dist/skills/defaults/llm-application/llm-evaluation.md +695 -0
- package/dist/skills/defaults/llm-application/prompt-engineering-patterns.md +449 -0
- package/dist/skills/defaults/llm-application/prompt-engineering.md +219 -0
- package/dist/skills/defaults/llm-application/rag-implementation.md +434 -0
- package/dist/skills/defaults/llm-application/similarity-search-patterns.md +560 -0
- package/dist/skills/defaults/llm-application/similarity-search.md +560 -0
- package/dist/skills/defaults/llm-application/vector-index-tuning.md +523 -0
- package/dist/skills/defaults/mobile/mobile-android-design.md +440 -0
- package/dist/skills/defaults/mobile/mobile-ios-design.md +266 -0
- package/dist/skills/defaults/monitoring/distributed-tracing.md +436 -0
- package/dist/skills/defaults/monitoring/grafana-dashboards.md +370 -0
- package/dist/skills/defaults/monitoring/prometheus-configuration.md +379 -0
- package/dist/skills/defaults/monitoring/slo-implementation.md +323 -0
- package/dist/skills/defaults/refactoring/code-refactoring.md +349 -0
- package/dist/skills/defaults/security/anti-reversing-techniques/SKILL.md +559 -0
- package/dist/skills/defaults/security/auditor.md +168 -0
- package/dist/skills/defaults/security/binary-analysis-patterns/SKILL.md +438 -0
- package/dist/skills/defaults/security/memory-forensics/SKILL.md +483 -0
- package/dist/skills/defaults/security/mtls-configuration.md +349 -0
- package/dist/skills/defaults/security/protocol-reverse-engineering/SKILL.md +520 -0
- package/dist/skills/defaults/security/sast-configuration.md +182 -0
- package/dist/skills/defaults/security/security.md +313 -0
- package/dist/skills/defaults/security/stride-analysis.md +273 -0
- package/dist/skills/defaults/security/threat-mitigation-mapping.md +290 -0
- package/dist/skills/defaults/systems/bash-defensive-patterns/SKILL.md +539 -0
- package/dist/skills/defaults/systems/bats-testing-patterns/SKILL.md +631 -0
- package/dist/skills/defaults/systems/go-concurrency-patterns.md +657 -0
- package/dist/skills/defaults/systems/memory-safety-patterns.md +605 -0
- package/dist/skills/defaults/systems/rust-async-patterns.md +519 -0
- package/dist/skills/defaults/systems/shellcheck-configuration/SKILL.md +456 -0
- package/dist/skills/defaults/team-collaboration/multi-reviewer-patterns.md +126 -0
- package/dist/skills/defaults/team-collaboration/parallel-feature-development.md +151 -0
- package/dist/skills/defaults/testing/javascript-testing-patterns.md +1021 -0
- package/dist/skills/defaults/testing/python-testing-patterns.md +351 -0
- package/dist/skills/defaults/testing/testing.md +332 -0
- package/dist/skills/defaults/workflows/context-driven-development.md +384 -0
- package/dist/skills/defaults/workflows/track-management.md +592 -0
- package/dist/skills/defaults/workflows/workflow-patterns.md +622 -0
- package/dist/skills/index.d.ts +11 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +129 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/utils/character.js +4 -4
- package/dist/utils/character.js.map +1 -1
- package/dist/utils/inputbar.d.ts.map +1 -1
- package/dist/utils/inputbar.js +7 -0
- package/dist/utils/inputbar.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: python-code-style
|
|
3
|
+
description: Python code style, linting, formatting, naming conventions, and documentation standards. Use when writing new code, reviewing style, configuring linters, writing docstrings, or establishing project standards.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Python Code Style & Documentation
|
|
7
|
+
|
|
8
|
+
Consistent code style and clear documentation make codebases maintainable and collaborative. This skill covers modern Python tooling, naming conventions, and documentation standards.
|
|
9
|
+
|
|
10
|
+
## When to Use This Skill
|
|
11
|
+
|
|
12
|
+
- Setting up linting and formatting for a new project
|
|
13
|
+
- Writing or reviewing docstrings
|
|
14
|
+
- Establishing team coding standards
|
|
15
|
+
- Configuring ruff, mypy, or pyright
|
|
16
|
+
- Reviewing code for style consistency
|
|
17
|
+
- Creating project documentation
|
|
18
|
+
|
|
19
|
+
## Core Concepts
|
|
20
|
+
|
|
21
|
+
### 1. Automated Formatting
|
|
22
|
+
|
|
23
|
+
Let tools handle formatting debates. Configure once, enforce automatically.
|
|
24
|
+
|
|
25
|
+
### 2. Consistent Naming
|
|
26
|
+
|
|
27
|
+
Follow PEP 8 conventions with meaningful, descriptive names.
|
|
28
|
+
|
|
29
|
+
### 3. Documentation as Code
|
|
30
|
+
|
|
31
|
+
Docstrings should be maintained alongside the code they describe.
|
|
32
|
+
|
|
33
|
+
### 4. Type Annotations
|
|
34
|
+
|
|
35
|
+
Modern Python code should include type hints for all public APIs.
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# Install modern tooling
|
|
41
|
+
pip install ruff mypy
|
|
42
|
+
|
|
43
|
+
# Configure in pyproject.toml
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 120
|
|
46
|
+
target-version = "py312" # Adjust based on your project's minimum Python version
|
|
47
|
+
|
|
48
|
+
[tool.mypy]
|
|
49
|
+
strict = true
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Fundamental Patterns
|
|
53
|
+
|
|
54
|
+
### Pattern 1: Modern Python Tooling
|
|
55
|
+
|
|
56
|
+
Use `ruff` as an all-in-one linter and formatter. It replaces flake8, isort, and black with a single fast tool.
|
|
57
|
+
|
|
58
|
+
```toml
|
|
59
|
+
# pyproject.toml
|
|
60
|
+
[tool.ruff]
|
|
61
|
+
line-length = 120
|
|
62
|
+
target-version = "py312" # Adjust based on your project's minimum Python version
|
|
63
|
+
|
|
64
|
+
[tool.ruff.lint]
|
|
65
|
+
select = [
|
|
66
|
+
"E", # pycodestyle errors
|
|
67
|
+
"W", # pycodestyle warnings
|
|
68
|
+
"F", # pyflakes
|
|
69
|
+
"I", # isort
|
|
70
|
+
"B", # flake8-bugbear
|
|
71
|
+
"C4", # flake8-comprehensions
|
|
72
|
+
"UP", # pyupgrade
|
|
73
|
+
"SIM", # flake8-simplify
|
|
74
|
+
]
|
|
75
|
+
ignore = ["E501"] # Line length handled by formatter
|
|
76
|
+
|
|
77
|
+
[tool.ruff.format]
|
|
78
|
+
quote-style = "double"
|
|
79
|
+
indent-style = "space"
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Run with:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
ruff check --fix . # Lint and auto-fix
|
|
86
|
+
ruff format . # Format code
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Pattern 2: Type Checking Configuration
|
|
90
|
+
|
|
91
|
+
Configure strict type checking for production code.
|
|
92
|
+
|
|
93
|
+
```toml
|
|
94
|
+
# pyproject.toml
|
|
95
|
+
[tool.mypy]
|
|
96
|
+
python_version = "3.12"
|
|
97
|
+
strict = true
|
|
98
|
+
warn_return_any = true
|
|
99
|
+
warn_unused_ignores = true
|
|
100
|
+
disallow_untyped_defs = true
|
|
101
|
+
disallow_incomplete_defs = true
|
|
102
|
+
|
|
103
|
+
[[tool.mypy.overrides]]
|
|
104
|
+
module = "tests.*"
|
|
105
|
+
disallow_untyped_defs = false
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Alternative: Use `pyright` for faster checking.
|
|
109
|
+
|
|
110
|
+
```toml
|
|
111
|
+
[tool.pyright]
|
|
112
|
+
pythonVersion = "3.12"
|
|
113
|
+
typeCheckingMode = "strict"
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Pattern 3: Naming Conventions
|
|
117
|
+
|
|
118
|
+
Follow PEP 8 with emphasis on clarity over brevity.
|
|
119
|
+
|
|
120
|
+
**Files and Modules:**
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# Good: Descriptive snake_case
|
|
124
|
+
user_repository.py
|
|
125
|
+
order_processing.py
|
|
126
|
+
http_client.py
|
|
127
|
+
|
|
128
|
+
# Avoid: Abbreviations
|
|
129
|
+
usr_repo.py
|
|
130
|
+
ord_proc.py
|
|
131
|
+
http_cli.py
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**Classes and Functions:**
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
# Classes: PascalCase
|
|
138
|
+
class UserRepository:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
class HTTPClientFactory: # Acronyms stay uppercase
|
|
142
|
+
pass
|
|
143
|
+
|
|
144
|
+
# Functions and variables: snake_case
|
|
145
|
+
def get_user_by_email(email: str) -> User | None:
|
|
146
|
+
retry_count = 3
|
|
147
|
+
max_connections = 100
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**Constants:**
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
# Module-level constants: SCREAMING_SNAKE_CASE
|
|
154
|
+
MAX_RETRY_ATTEMPTS = 3
|
|
155
|
+
DEFAULT_TIMEOUT_SECONDS = 30
|
|
156
|
+
API_BASE_URL = "https://api.example.com"
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Pattern 4: Import Organization
|
|
160
|
+
|
|
161
|
+
Group imports in a consistent order: standard library, third-party, local.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
# Standard library
|
|
165
|
+
import os
|
|
166
|
+
from collections.abc import Callable
|
|
167
|
+
from typing import Any
|
|
168
|
+
|
|
169
|
+
# Third-party packages
|
|
170
|
+
import httpx
|
|
171
|
+
from pydantic import BaseModel
|
|
172
|
+
from sqlalchemy import Column
|
|
173
|
+
|
|
174
|
+
# Local imports
|
|
175
|
+
from myproject.models import User
|
|
176
|
+
from myproject.services import UserService
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Use absolute imports exclusively:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
# Preferred
|
|
183
|
+
from myproject.utils import retry_decorator
|
|
184
|
+
|
|
185
|
+
# Avoid relative imports
|
|
186
|
+
from ..utils import retry_decorator
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Advanced Patterns
|
|
190
|
+
|
|
191
|
+
### Pattern 5: Google-Style Docstrings
|
|
192
|
+
|
|
193
|
+
Write docstrings for all public classes, methods, and functions.
|
|
194
|
+
|
|
195
|
+
**Simple Function:**
|
|
196
|
+
|
|
197
|
+
```python
|
|
198
|
+
def get_user(user_id: str) -> User:
|
|
199
|
+
"""Retrieve a user by their unique identifier."""
|
|
200
|
+
...
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
**Complex Function:**
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
def process_batch(
|
|
207
|
+
items: list[Item],
|
|
208
|
+
max_workers: int = 4,
|
|
209
|
+
on_progress: Callable[[int, int], None] | None = None,
|
|
210
|
+
) -> BatchResult:
|
|
211
|
+
"""Process items concurrently using a worker pool.
|
|
212
|
+
|
|
213
|
+
Processes each item in the batch using the configured number of
|
|
214
|
+
workers. Progress can be monitored via the optional callback.
|
|
215
|
+
|
|
216
|
+
Args:
|
|
217
|
+
items: The items to process. Must not be empty.
|
|
218
|
+
max_workers: Maximum concurrent workers. Defaults to 4.
|
|
219
|
+
on_progress: Optional callback receiving (completed, total) counts.
|
|
220
|
+
|
|
221
|
+
Returns:
|
|
222
|
+
BatchResult containing succeeded items and any failures with
|
|
223
|
+
their associated exceptions.
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
ValueError: If items is empty.
|
|
227
|
+
ProcessingError: If the batch cannot be processed.
|
|
228
|
+
|
|
229
|
+
Example:
|
|
230
|
+
>>> result = process_batch(items, max_workers=8)
|
|
231
|
+
>>> print(f"Processed {len(result.succeeded)} items")
|
|
232
|
+
"""
|
|
233
|
+
...
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
**Class Docstring:**
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
class UserService:
|
|
240
|
+
"""Service for managing user operations.
|
|
241
|
+
|
|
242
|
+
Provides methods for creating, retrieving, updating, and
|
|
243
|
+
deleting users with proper validation and error handling.
|
|
244
|
+
|
|
245
|
+
Attributes:
|
|
246
|
+
repository: The data access layer for user persistence.
|
|
247
|
+
logger: Logger instance for operation tracking.
|
|
248
|
+
|
|
249
|
+
Example:
|
|
250
|
+
>>> service = UserService(repository, logger)
|
|
251
|
+
>>> user = service.create_user(CreateUserInput(...))
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
def __init__(self, repository: UserRepository, logger: Logger) -> None:
|
|
255
|
+
"""Initialize the user service.
|
|
256
|
+
|
|
257
|
+
Args:
|
|
258
|
+
repository: Data access layer for users.
|
|
259
|
+
logger: Logger for tracking operations.
|
|
260
|
+
"""
|
|
261
|
+
self.repository = repository
|
|
262
|
+
self.logger = logger
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
### Pattern 6: Line Length and Formatting
|
|
266
|
+
|
|
267
|
+
Set line length to 120 characters for modern displays while maintaining readability.
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
# Good: Readable line breaks
|
|
271
|
+
def create_user(
|
|
272
|
+
email: str,
|
|
273
|
+
name: str,
|
|
274
|
+
role: UserRole = UserRole.MEMBER,
|
|
275
|
+
notify: bool = True,
|
|
276
|
+
) -> User:
|
|
277
|
+
...
|
|
278
|
+
|
|
279
|
+
# Good: Chain method calls clearly
|
|
280
|
+
result = (
|
|
281
|
+
db.query(User)
|
|
282
|
+
.filter(User.active == True)
|
|
283
|
+
.order_by(User.created_at.desc())
|
|
284
|
+
.limit(10)
|
|
285
|
+
.all()
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# Good: Format long strings
|
|
289
|
+
error_message = (
|
|
290
|
+
f"Failed to process user {user_id}: "
|
|
291
|
+
f"received status {response.status_code} "
|
|
292
|
+
f"with body {response.text[:100]}"
|
|
293
|
+
)
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
### Pattern 7: Project Documentation
|
|
297
|
+
|
|
298
|
+
**README Structure:**
|
|
299
|
+
|
|
300
|
+
```markdown
|
|
301
|
+
# Project Name
|
|
302
|
+
|
|
303
|
+
Brief description of what the project does.
|
|
304
|
+
|
|
305
|
+
## Installation
|
|
306
|
+
|
|
307
|
+
\`\`\`bash
|
|
308
|
+
pip install myproject
|
|
309
|
+
\`\`\`
|
|
310
|
+
|
|
311
|
+
## Quick Start
|
|
312
|
+
|
|
313
|
+
\`\`\`python
|
|
314
|
+
from myproject import Client
|
|
315
|
+
|
|
316
|
+
client = Client(api_key="...")
|
|
317
|
+
result = client.process(data)
|
|
318
|
+
\`\`\`
|
|
319
|
+
|
|
320
|
+
## Configuration
|
|
321
|
+
|
|
322
|
+
Document environment variables and configuration options.
|
|
323
|
+
|
|
324
|
+
## Development
|
|
325
|
+
|
|
326
|
+
\`\`\`bash
|
|
327
|
+
pip install -e ".[dev]"
|
|
328
|
+
pytest
|
|
329
|
+
\`\`\`
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
**CHANGELOG Format (Keep a Changelog):**
|
|
333
|
+
|
|
334
|
+
```markdown
|
|
335
|
+
# Changelog
|
|
336
|
+
|
|
337
|
+
## [Unreleased]
|
|
338
|
+
|
|
339
|
+
### Added
|
|
340
|
+
- New feature X
|
|
341
|
+
|
|
342
|
+
### Changed
|
|
343
|
+
- Modified behavior of Y
|
|
344
|
+
|
|
345
|
+
### Fixed
|
|
346
|
+
- Bug in Z
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
## Best Practices Summary
|
|
350
|
+
|
|
351
|
+
1. **Use ruff** - Single tool for linting and formatting
|
|
352
|
+
2. **Enable strict mypy** - Catch type errors before runtime
|
|
353
|
+
3. **120 character lines** - Modern standard for readability
|
|
354
|
+
4. **Descriptive names** - Clarity over brevity
|
|
355
|
+
5. **Absolute imports** - More maintainable than relative
|
|
356
|
+
6. **Google-style docstrings** - Consistent, readable documentation
|
|
357
|
+
7. **Document public APIs** - Every public function needs a docstring
|
|
358
|
+
8. **Keep docs updated** - Treat documentation as code
|
|
359
|
+
9. **Automate in CI** - Run linters on every commit
|
|
360
|
+
10. **Target Python 3.10+** - For new projects, Python 3.12+ is recommended for modern language features
|
|
@@ -0,0 +1,368 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: python-configuration
|
|
3
|
+
description: Python configuration management via environment variables and typed settings. Use when externalizing config, setting up pydantic-settings, managing secrets, or implementing environment-specific behavior.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Python Configuration Management
|
|
7
|
+
|
|
8
|
+
Externalize configuration from code using environment variables and typed settings. Well-managed configuration enables the same code to run in any environment without modification.
|
|
9
|
+
|
|
10
|
+
## When to Use This Skill
|
|
11
|
+
|
|
12
|
+
- Setting up a new project's configuration system
|
|
13
|
+
- Migrating from hardcoded values to environment variables
|
|
14
|
+
- Implementing pydantic-settings for typed configuration
|
|
15
|
+
- Managing secrets and sensitive values
|
|
16
|
+
- Creating environment-specific settings (dev/staging/prod)
|
|
17
|
+
- Validating configuration at application startup
|
|
18
|
+
|
|
19
|
+
## Core Concepts
|
|
20
|
+
|
|
21
|
+
### 1. Externalized Configuration
|
|
22
|
+
|
|
23
|
+
All environment-specific values (URLs, secrets, feature flags) come from environment variables, not code.
|
|
24
|
+
|
|
25
|
+
### 2. Typed Settings
|
|
26
|
+
|
|
27
|
+
Parse and validate configuration into typed objects at startup, not scattered throughout code.
|
|
28
|
+
|
|
29
|
+
### 3. Fail Fast
|
|
30
|
+
|
|
31
|
+
Validate all required configuration at application boot. Missing config should crash immediately with a clear message.
|
|
32
|
+
|
|
33
|
+
### 4. Sensible Defaults
|
|
34
|
+
|
|
35
|
+
Provide reasonable defaults for local development while requiring explicit values for sensitive settings.
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from pydantic_settings import BaseSettings
|
|
41
|
+
from pydantic import Field
|
|
42
|
+
|
|
43
|
+
class Settings(BaseSettings):
|
|
44
|
+
database_url: str = Field(alias="DATABASE_URL")
|
|
45
|
+
api_key: str = Field(alias="API_KEY")
|
|
46
|
+
debug: bool = Field(default=False, alias="DEBUG")
|
|
47
|
+
|
|
48
|
+
settings = Settings() # Loads from environment
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Fundamental Patterns
|
|
52
|
+
|
|
53
|
+
### Pattern 1: Typed Settings with Pydantic
|
|
54
|
+
|
|
55
|
+
Create a central settings class that loads and validates all configuration.
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from pydantic_settings import BaseSettings
|
|
59
|
+
from pydantic import Field, PostgresDsn, ValidationError
|
|
60
|
+
import sys
|
|
61
|
+
|
|
62
|
+
class Settings(BaseSettings):
|
|
63
|
+
"""Application configuration loaded from environment variables."""
|
|
64
|
+
|
|
65
|
+
# Database
|
|
66
|
+
db_host: str = Field(alias="DB_HOST")
|
|
67
|
+
db_port: int = Field(default=5432, alias="DB_PORT")
|
|
68
|
+
db_name: str = Field(alias="DB_NAME")
|
|
69
|
+
db_user: str = Field(alias="DB_USER")
|
|
70
|
+
db_password: str = Field(alias="DB_PASSWORD")
|
|
71
|
+
|
|
72
|
+
# Redis
|
|
73
|
+
redis_url: str = Field(default="redis://localhost:6379", alias="REDIS_URL")
|
|
74
|
+
|
|
75
|
+
# API Keys
|
|
76
|
+
api_secret_key: str = Field(alias="API_SECRET_KEY")
|
|
77
|
+
|
|
78
|
+
# Feature flags
|
|
79
|
+
enable_new_feature: bool = Field(default=False, alias="ENABLE_NEW_FEATURE")
|
|
80
|
+
|
|
81
|
+
model_config = {
|
|
82
|
+
"env_file": ".env",
|
|
83
|
+
"env_file_encoding": "utf-8",
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
# Create singleton instance at module load
|
|
87
|
+
try:
|
|
88
|
+
settings = Settings()
|
|
89
|
+
except ValidationError as e:
|
|
90
|
+
print(f"Configuration error:\n{e}")
|
|
91
|
+
sys.exit(1)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Import `settings` throughout your application:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from myapp.config import settings
|
|
98
|
+
|
|
99
|
+
def get_database_connection():
|
|
100
|
+
return connect(
|
|
101
|
+
host=settings.db_host,
|
|
102
|
+
port=settings.db_port,
|
|
103
|
+
database=settings.db_name,
|
|
104
|
+
)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Pattern 2: Fail Fast on Missing Configuration
|
|
108
|
+
|
|
109
|
+
Required settings should crash the application immediately with a clear error.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
from pydantic_settings import BaseSettings
|
|
113
|
+
from pydantic import Field, ValidationError
|
|
114
|
+
import sys
|
|
115
|
+
|
|
116
|
+
class Settings(BaseSettings):
|
|
117
|
+
# Required - no default means it must be set
|
|
118
|
+
api_key: str = Field(alias="API_KEY")
|
|
119
|
+
database_url: str = Field(alias="DATABASE_URL")
|
|
120
|
+
|
|
121
|
+
# Optional with defaults
|
|
122
|
+
log_level: str = Field(default="INFO", alias="LOG_LEVEL")
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
settings = Settings()
|
|
126
|
+
except ValidationError as e:
|
|
127
|
+
print("=" * 60)
|
|
128
|
+
print("CONFIGURATION ERROR")
|
|
129
|
+
print("=" * 60)
|
|
130
|
+
for error in e.errors():
|
|
131
|
+
field = error["loc"][0]
|
|
132
|
+
print(f" - {field}: {error['msg']}")
|
|
133
|
+
print("\nPlease set the required environment variables.")
|
|
134
|
+
sys.exit(1)
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
A clear error at startup is better than a cryptic `None` failure mid-request.
|
|
138
|
+
|
|
139
|
+
### Pattern 3: Local Development Defaults
|
|
140
|
+
|
|
141
|
+
Provide sensible defaults for local development while requiring explicit values for secrets.
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
class Settings(BaseSettings):
|
|
145
|
+
# Has local default, but prod will override
|
|
146
|
+
db_host: str = Field(default="localhost", alias="DB_HOST")
|
|
147
|
+
db_port: int = Field(default=5432, alias="DB_PORT")
|
|
148
|
+
|
|
149
|
+
# Always required - no default for secrets
|
|
150
|
+
db_password: str = Field(alias="DB_PASSWORD")
|
|
151
|
+
api_secret_key: str = Field(alias="API_SECRET_KEY")
|
|
152
|
+
|
|
153
|
+
# Development convenience
|
|
154
|
+
debug: bool = Field(default=False, alias="DEBUG")
|
|
155
|
+
|
|
156
|
+
model_config = {"env_file": ".env"}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Create a `.env` file for local development (never commit this):
|
|
160
|
+
|
|
161
|
+
```bash
|
|
162
|
+
# .env (add to .gitignore)
|
|
163
|
+
DB_PASSWORD=local_dev_password
|
|
164
|
+
API_SECRET_KEY=dev-secret-key
|
|
165
|
+
DEBUG=true
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### Pattern 4: Namespaced Environment Variables
|
|
169
|
+
|
|
170
|
+
Prefix related variables for clarity and easy debugging.
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
# Database configuration
|
|
174
|
+
DB_HOST=localhost
|
|
175
|
+
DB_PORT=5432
|
|
176
|
+
DB_NAME=myapp
|
|
177
|
+
DB_USER=admin
|
|
178
|
+
DB_PASSWORD=secret
|
|
179
|
+
|
|
180
|
+
# Redis configuration
|
|
181
|
+
REDIS_URL=redis://localhost:6379
|
|
182
|
+
REDIS_MAX_CONNECTIONS=10
|
|
183
|
+
|
|
184
|
+
# Authentication
|
|
185
|
+
AUTH_SECRET_KEY=your-secret-key
|
|
186
|
+
AUTH_TOKEN_EXPIRY_SECONDS=3600
|
|
187
|
+
AUTH_ALGORITHM=HS256
|
|
188
|
+
|
|
189
|
+
# Feature flags
|
|
190
|
+
FEATURE_NEW_CHECKOUT=true
|
|
191
|
+
FEATURE_BETA_UI=false
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
Makes `env | grep DB_` useful for debugging.
|
|
195
|
+
|
|
196
|
+
## Advanced Patterns
|
|
197
|
+
|
|
198
|
+
### Pattern 5: Type Coercion
|
|
199
|
+
|
|
200
|
+
Pydantic handles common conversions automatically.
|
|
201
|
+
|
|
202
|
+
```python
|
|
203
|
+
from pydantic_settings import BaseSettings
|
|
204
|
+
from pydantic import Field, field_validator
|
|
205
|
+
|
|
206
|
+
class Settings(BaseSettings):
|
|
207
|
+
# Automatically converts "true", "1", "yes" to True
|
|
208
|
+
debug: bool = False
|
|
209
|
+
|
|
210
|
+
# Automatically converts string to int
|
|
211
|
+
max_connections: int = 100
|
|
212
|
+
|
|
213
|
+
# Parse comma-separated string to list
|
|
214
|
+
allowed_hosts: list[str] = Field(default_factory=list)
|
|
215
|
+
|
|
216
|
+
@field_validator("allowed_hosts", mode="before")
|
|
217
|
+
@classmethod
|
|
218
|
+
def parse_allowed_hosts(cls, v: str | list[str]) -> list[str]:
|
|
219
|
+
if isinstance(v, str):
|
|
220
|
+
return [host.strip() for host in v.split(",") if host.strip()]
|
|
221
|
+
return v
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Usage:
|
|
225
|
+
|
|
226
|
+
```bash
|
|
227
|
+
ALLOWED_HOSTS=example.com,api.example.com,localhost
|
|
228
|
+
MAX_CONNECTIONS=50
|
|
229
|
+
DEBUG=true
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Pattern 6: Environment-Specific Configuration
|
|
233
|
+
|
|
234
|
+
Use an environment enum to switch behavior.
|
|
235
|
+
|
|
236
|
+
```python
|
|
237
|
+
from enum import Enum
|
|
238
|
+
from pydantic_settings import BaseSettings
|
|
239
|
+
from pydantic import Field, computed_field
|
|
240
|
+
|
|
241
|
+
class Environment(str, Enum):
|
|
242
|
+
LOCAL = "local"
|
|
243
|
+
STAGING = "staging"
|
|
244
|
+
PRODUCTION = "production"
|
|
245
|
+
|
|
246
|
+
class Settings(BaseSettings):
|
|
247
|
+
environment: Environment = Field(
|
|
248
|
+
default=Environment.LOCAL,
|
|
249
|
+
alias="ENVIRONMENT",
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
# Settings that vary by environment
|
|
253
|
+
log_level: str = Field(default="DEBUG", alias="LOG_LEVEL")
|
|
254
|
+
|
|
255
|
+
@computed_field
|
|
256
|
+
@property
|
|
257
|
+
def is_production(self) -> bool:
|
|
258
|
+
return self.environment == Environment.PRODUCTION
|
|
259
|
+
|
|
260
|
+
@computed_field
|
|
261
|
+
@property
|
|
262
|
+
def is_local(self) -> bool:
|
|
263
|
+
return self.environment == Environment.LOCAL
|
|
264
|
+
|
|
265
|
+
# Usage
|
|
266
|
+
if settings.is_production:
|
|
267
|
+
configure_production_logging()
|
|
268
|
+
else:
|
|
269
|
+
configure_debug_logging()
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
### Pattern 7: Nested Configuration Groups
|
|
273
|
+
|
|
274
|
+
Organize related settings into nested models.
|
|
275
|
+
|
|
276
|
+
```python
|
|
277
|
+
from pydantic import BaseModel
|
|
278
|
+
from pydantic_settings import BaseSettings
|
|
279
|
+
|
|
280
|
+
class DatabaseSettings(BaseModel):
|
|
281
|
+
host: str = "localhost"
|
|
282
|
+
port: int = 5432
|
|
283
|
+
name: str
|
|
284
|
+
user: str
|
|
285
|
+
password: str
|
|
286
|
+
|
|
287
|
+
class RedisSettings(BaseModel):
|
|
288
|
+
url: str = "redis://localhost:6379"
|
|
289
|
+
max_connections: int = 10
|
|
290
|
+
|
|
291
|
+
class Settings(BaseSettings):
|
|
292
|
+
database: DatabaseSettings
|
|
293
|
+
redis: RedisSettings
|
|
294
|
+
debug: bool = False
|
|
295
|
+
|
|
296
|
+
model_config = {
|
|
297
|
+
"env_nested_delimiter": "__",
|
|
298
|
+
"env_file": ".env",
|
|
299
|
+
}
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
Environment variables use double underscore for nesting:
|
|
303
|
+
|
|
304
|
+
```bash
|
|
305
|
+
DATABASE__HOST=db.example.com
|
|
306
|
+
DATABASE__PORT=5432
|
|
307
|
+
DATABASE__NAME=myapp
|
|
308
|
+
DATABASE__USER=admin
|
|
309
|
+
DATABASE__PASSWORD=secret
|
|
310
|
+
REDIS__URL=redis://redis.example.com:6379
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### Pattern 8: Secrets from Files
|
|
314
|
+
|
|
315
|
+
For container environments, read secrets from mounted files.
|
|
316
|
+
|
|
317
|
+
```python
|
|
318
|
+
from pydantic_settings import BaseSettings
|
|
319
|
+
from pydantic import Field
|
|
320
|
+
from pathlib import Path
|
|
321
|
+
|
|
322
|
+
class Settings(BaseSettings):
|
|
323
|
+
# Read from environment variable or file
|
|
324
|
+
db_password: str = Field(alias="DB_PASSWORD")
|
|
325
|
+
|
|
326
|
+
model_config = {
|
|
327
|
+
"secrets_dir": "/run/secrets", # Docker secrets location
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Pydantic will look for `/run/secrets/db_password` if the env var isn't set.
|
|
332
|
+
|
|
333
|
+
### Pattern 9: Configuration Validation
|
|
334
|
+
|
|
335
|
+
Add custom validation for complex requirements.
|
|
336
|
+
|
|
337
|
+
```python
|
|
338
|
+
from pydantic_settings import BaseSettings
|
|
339
|
+
from pydantic import Field, model_validator
|
|
340
|
+
|
|
341
|
+
class Settings(BaseSettings):
|
|
342
|
+
db_host: str = Field(alias="DB_HOST")
|
|
343
|
+
db_port: int = Field(alias="DB_PORT")
|
|
344
|
+
read_replica_host: str | None = Field(default=None, alias="READ_REPLICA_HOST")
|
|
345
|
+
read_replica_port: int = Field(default=5432, alias="READ_REPLICA_PORT")
|
|
346
|
+
|
|
347
|
+
@model_validator(mode="after")
|
|
348
|
+
def validate_replica_settings(self):
|
|
349
|
+
if self.read_replica_host and self.read_replica_port == self.db_port:
|
|
350
|
+
if self.read_replica_host == self.db_host:
|
|
351
|
+
raise ValueError(
|
|
352
|
+
"Read replica cannot be the same as primary database"
|
|
353
|
+
)
|
|
354
|
+
return self
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
## Best Practices Summary
|
|
358
|
+
|
|
359
|
+
1. **Never hardcode config** - All environment-specific values from env vars
|
|
360
|
+
2. **Use typed settings** - Pydantic-settings with validation
|
|
361
|
+
3. **Fail fast** - Crash on missing required config at startup
|
|
362
|
+
4. **Provide dev defaults** - Make local development easy
|
|
363
|
+
5. **Never commit secrets** - Use `.env` files (gitignored) or secret managers
|
|
364
|
+
6. **Namespace variables** - `DB_HOST`, `REDIS_URL` for clarity
|
|
365
|
+
7. **Import settings singleton** - Don't call `os.getenv()` throughout code
|
|
366
|
+
8. **Document all variables** - README should list required env vars
|
|
367
|
+
9. **Validate early** - Check config correctness at boot time
|
|
368
|
+
10. **Use secrets_dir** - Support mounted secrets in containers
|