python-best-practices
Skill0 starsChanged 4 months agoMITView on GitHub
Enterprise Python coding standard for AI agents. Load BEFORE writing, modifying, or reviewing any Python code (.py files, FastAPI routes, SQLAlchemy models, pytest tests, Pydantic schemas, async code, Alembic migrations). Covers architecture layering, naming, type safety, error handling, logging, security, DB access, FastAPI, async, performance, testing, and tooling (ruff/black/mypy).
- Reads credentials
15 other projects use a version of this.
Adopted by
Most recently taken up by
- baekenough/oh-my-customcodetheir own version, first seen Oct 3, 2026
- The-AIOS/aiostheir own version, first seen Sep 24, 2026
- excatt/superclaude-plusplustheir own version, first seen Sep 7, 2026
- amirrezaalasti/codescribetheir own version, first seen Aug 3, 2026
- tomroberts92/skillstheir own version, first seen Jun 25, 2026
- reformovo/skillstheir own version, first seen Jun 24, 2026
Used with
Projects with it also use typescript-best-practices, frontend-design and 1 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
ofershapSkilltypescript-best-practices
Also in 3 projects that use this
VercelSkillfrontend-design
Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, artifacts, posters, or applications (examples include websites, landing pages, dashboards, React components, HTML/CSS layouts, or when styling/beautifying any web UI). Generates creative, polished code and UI design that avoids generic AI aesthetics.
Also in 4 projects that use this
MicrosoftSkillskill-creator
Guide for creating effective GitHub Copilot skills (.github/skills/) in this repository. Use when creating a new skill, updating an existing skill, or when asked about skill structure, format, or best practices for the vscode-documentdb project.
Also in 4 projects that use this
Other versions15 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 15
- rohitg00/awesome-claude-code-toolkit★ 2.7ksame name
- The-AIOS/aios★ 69same name
- baekenough/oh-my-customcode★ 43same name
- jefflester/claude-skills-supercharged★ 42same name
- excatt/superclaude-plusplus★ 14same name
- cisco-open/ai-harness-toolkit★ 13same name
- arnabdeypolimi/claude_code_setup★ 4same name
- Sanskar015/claude-skills-supercharged★ 3same name
- amirrezaalasti/codescribe★ 2same name
- b12consulting/skills★ 2same name
5 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository7 other files it gives its agents.
The file
Show its rules and text
We split this skill into the rules it gives an agent
14 rules. 0 are common, 5 are distinctive, and 9 are very specific to this project.
0
Common
Most of the 13 edited versions we read keep these.
5
Distinctive
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 9
When this conflicts with an in-repo convention, follow the repo and say so.
- Very specific: line 48
Don't encode the type in the name (id_to_name_dict, order_list).
- Very specific: line 50
Keep __init__.py thin: re-export only a curated public API, and define __all__ when you do.
- Very specific: line 52
No import-time side effects: no DB or network connections, no load_dotenv() in library modules.
- Very specific: line 61
Never mutate a caller-owned argument unless the name says so (_in_place).
- Very specific: line 120
Read-modify-write on money or stock: with_for_update() or optimistic versioning (version_id_col).
- Very specific: line 122
Every schema change ships an Alembic revision: autogenerate, then hand-edit.
- Very specific: line 141
Never a bare asyncio.create_task: keep a reference, await it, or use a TaskGroup, or it can be garbage-collected and its exception vanishes.
- Very specific: line 142
Every outbound call gets a timeout (asyncio.timeout() or the client's).
- Very specific: line 151
Every cache has an explicit key, TTL, and invalidation story: functools.cache/lru_cache for pure in-process functions, Redis for …
- Distinctive: line 168
All pass locally and in CI before code is complete:
- Distinctive: line 198
Never invent business rules: if credit limits, tax treatment, rounding, statuses, or SLAs are ambiguous, ask.
- Distinctive: line 199
Never break a public Python API (signature, default, return type, import path) to apply a rule here (one class per file, keyword-only …
- Distinctive: line 200
Add no dependency without saying why and confirming.
“Common” is measured: kept by at least 6 in 10 of the 13 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Python Best Practices (Enterprise Standard)
Target: Python 3.12+, FastAPI, Pydantic, SQLAlchemy 2.0, Alembic, pytest. When this conflicts with an in-repo convention, follow the repo and say so.
1. Project Structure
app/
main.py # ASGI app factory, middleware, router registration only
api/ # HTTP layer: routers, dependencies, exception handlers
v1/routes/
deps.py
services/ # application services (use cases); orchestrate repositories
repositories/ # all persistence access
models/ # SQLAlchemy ORM entities (persistence shape)
schemas/ # Pydantic request/response DTOs (wire shape)
domain/ # pure business types, value objects, domain services, domain exceptions (no I/O)
core/ # settings, logging config, security, constants
db/ # engine/session factory, base metadata, migrations/ (Alembic)
clients/ # outbound HTTP/queue/third-party adapters
utils/ # small generic helpers
tests/
unit/ integration/ e2e/ conftest.py factories/| Layer | May depend on | Must never |
api | schemas, services, deps | touch Session, ORM models, or SQL |
services | repositories, domain, clients | import FastAPI, Request, or HTTPException |
repositories | models, db | contain business rules |
domain | stdlib only | import SQLAlchemy, FastAPI, Pydantic-web concerns |
utils | stdlib | import app.* |
- Services may receive ORM objects from repositories; there is no mapping layer between them.
models/is not framework-independent: entity behaviour that must be unit-tested without a database belongs indomain/.- Once a layer exceeds ~10 files, group it by aggregate/feature subpackage (
services/orders/,services/invoicing/), not by pattern.
2. Naming and Imports
- Booleans take an
is_/has_/can_/should_prefix. - Units and currency belong in the name:
timeout_seconds,amount_inr_paise. - Don't encode the type in the name (
id_to_name_dict,order_list). - Absolute imports for first-party code; relative imports only inside a tightly cohesive package.
- Keep
__init__.pythin: re-export only a curated public API, and define__all__when you do. - Fix an import cycle by moving the shared type into
domain/or depending on a Protocol; a function-local import is a last resort and carries a comment saying why. - No import-time side effects: no DB or network connections, no
load_dotenv()in library modules.
3. Functions
- ≤ 30 lines, ≤ 4 parameters, cyclomatic complexity ≤ 8; past that, extract.
- Type hints on every parameter and return value, including
-> None. - Optional and boolean parameters are keyword-only (
def send(*, dry_run: bool = False) -> None:); never pass a bare boolean positionally. - No
**kwargspass-through where real parameters belong. - One return type: raise instead of returning a sentinel (not
Order | None | bool);X | Nonemeans genuinely absent, never a way to dodge error handling. - Never mutate a caller-owned argument unless the name says so (
_in_place).
4. Classes
- A class with one method and no state is a function.
- One class per file. Each class lives in its own module, named after the class in snake_case (
OrderService→order_service.py); five classes means five files. The only exception is a private helper (e.g. a small frozen dataclass) used exclusively by the class it sits next to. @dataclass(frozen=True, slots=True)for value objects; PydanticBaseModelonly at I/O boundaries (validation/serialization); plain classes for services.- Inject collaborators (sessions, HTTP clients, settings) through
__init__; never construct them inside the class. - Inheritance depth ≤ 2.
- A class over ~200 lines or with > 7 public methods gets split.
- Define
__repr__.
5. Type Safety
- PEP 695 syntax (
type Alias = ...,class Repository[T]:,def first[T](items: Sequence[T]) -> T | None:) and builtin generics; neverList,Dict,Optional,Union. Protocol(not ABC) for ports, defined in the inner layer; outer adapters satisfy it structurally without importing it.TypedDictfor fixed-shape dicts crossing boundaries (external JSON).NewTypefor IDs (CustomerId = NewType("CustomerId", int)); a PEP 695typealias cannot express it and does not stop IDs mixing.Literal/Enuminstead of magic strings;Finalon module constants.Anyneeds a justifying comment; preferobjectplus narrowing, or onecast()at a well-marked seam.mypy --strictallows explicitAny, and ruffANN401flags only a top-levelAny(includingAny | None) parameter or return annotation (a justified one carries# noqa: ANN401), so nestedAny(dict[str, Any]), variable annotations, andcastare caught only in review unless mypydisallow_any_explicitis on.assert isinstance(...)narrowing only in tests; production code uses explicit checks that raise.
6. Error Handling
- One hierarchy rooted in
AppError;DomainError(AppError)for business-rule violations; specific errors subclass per bounded context and carry the identifying values as attributes (CreditLimitExceededError(requested, available)). except Exceptiononly at a top-level boundary (request handler, worker loop, CLI entrypoint), logging withexc_info=True, then re-raising or failing the unit of work.- Exception messages never carry secrets, tokens, PII, or raw SQL.
- Retry only genuinely transient faults: bounded attempts, jittered backoff, idempotent operations only.
7. Logging
- One module-level
logger = logging.getLogger(__name__).print()is banned in application code (CLI user-facing output excepted). - Event-name message plus structured extras:
logger.info("order_credit_blocked", extra={"order_id": order.id, "shortfall": str(gap)}). Any interpolation is lazy%s, never an f-string. - Correlation ID: middleware generates or propagates a request ID into a
ContextVar, alogging.Filterinjects it into every record, and outbound calls forward it asX-Request-ID. - Mask at the logging layer (a redacting filter), not by trusting call sites. Never log passwords, tokens, API keys, full card/bank numbers, OTPs, auth headers, or full request bodies.
- Log security events: authentication success and failure, authorization failure, input-validation failure, and sensitive-data access, each with the actor, the source, and the correlation ID.
- No
INFOinside loops. - Configure handlers and format once at startup (
core/logging.py); modules never callbasicConfig.
8. Security
- Secrets load through a typed
pydantic-settingsSettingsasSecretStr, kept out ofreprand tracebacks. No hardcoded credentials, keys, or connection strings, not even in tests, defaults, or comments. - Validate at the boundary with Pydantic (exact types,
Fieldbounds,extra="forbid", allow-lists over deny-lists) and trust the data inside the core. - Uploads: allow-list extensions, verify the content matches the extension (magic bytes or a content-validation library), and enforce a size limit; never trust the client-supplied
Content-Type. - Password hashing, with the work factor always stated: Argon2id (m ≥ 19 MiB, t = 2, p = 1, or m ≥ 46 MiB, t = 1, p = 1); scrypt (N ≥ 2^17, r = 8, p = 1) if Argon2id is unavailable; bcrypt (cost ≥ 10, 72-byte input limit) for legacy systems only; PBKDF2-HMAC-SHA-256 ≥ 600,000 iterations (SHA-512 ≥ 210,000) where FIPS-140 compliance is required.
- Credential policy: minimum 8 characters (15 strongly recommended where MFA is absent), permit at least 64, no composition rules, failed-login counter bound to the account not the source IP, generic login errors.
- JWTs: verify signature,
alg,aud,iss, andexp; short TTL; no secrets in the payload. Compare secrets withhmac.compare_digest. - AuthZ: deny by default, enforced on every endpoint except the unauthenticated health probes by a dependency (router-level
dependencies=[Depends(require_role(...))]for cross-cutting auth); object-level ownership/tenancy checked in the service or repository query (WHERE tenant_id = :tenant). - Security headers: HSTS, a CSP with
frame-ancestors,X-Content-Type-Options: nosniff,Referrer-Policy. CORS: explicit origin allow-list, no wildcard origin on any response carrying sensitive data, and neverallow_origins=["*"]with credentials. - TLS certificate verification always on: never
verify=False. - SSRF and path traversal: allow-list outbound URLs; confine file paths with
Path.resolve().is_relative_to(base).
9. Database (SQLAlchemy 2.0 + Alembic)
- Repositories expose intent-named methods (
find_unpaid_by_customer(customer_id)) and are the only code that builds or executes queries. Services touch the session only to own the transaction and hand it to repositories; routes never receive it. - 2.0 style:
DeclarativeBasewithMapped[...]/mapped_column(...);select()executed viasession.scalars(stmt); never the legacyQueryAPI. - One transaction per unit of work (
with session.begin():or aunit_of_workcontext manager); repositories never commit; nevercommit()per record inside a loop (a batch job commits once per batch). A unit of work spanning several aggregates usually means wrong boundaries; make cross-aggregate consistency asynchronous. - One session per request from a
yielddependency (with Session(engine) as session: yield session). Never a module-global session, and never one shared across threads or concurrent tasks (anAsyncSessioninside aTaskGroupincluded). - Pool: set
pool_size,max_overflow,pool_pre_ping=True, andpool_recycleto stated values, overriding the defaults (5, 10, -1, pre-ping off).pool_size/max_overflowapply only toQueuePool(AsyncAdaptedQueuePoolundercreate_async_engine), not toNullPoolor theSingletonThreadPoolused for SQLite:memory:tests. - Relationships:
lazy="raise"by default, loading explicitly withselectinload/joinedload;lazy="raise_on_sql"is a different strategy, not a synonym. Raise-loading does not apply within the unit-of-work flush, so a lazy load thatSession.flush()needs still runs. Always defineback_populatesand an explicitcascade/passive_deletespolicy. - Read-modify-write on money or stock:
with_for_update()or optimistic versioning (version_id_col). - Python side:
Decimalorintminor units for money, neverfloat; timezone-aware UTCdatetimes. - Every schema change ships an Alembic revision: autogenerate, then hand-edit; a working, tested
downgrade().
10. FastAPI
- Thin routes: validate input via schema, call one service method, return a response model. ≤ 15 lines, zero business logic,
ifchains, or SQL. Annotated[X, Depends(...)]for current user, settings, and services.- Annotate the return type (
-> OrderOut); addresponse_model=only where the response genuinely differs from what the function returns (it wins if both are set). Always setstatus_codeexplicitly. Omit absent members rather than emittingnull:response_model_exclude_none=True(exclude_unsetwhere anullis a documented state). - Separate
...In/...Out/...Patchschemas; never return ORM objects from a route. @app.exception_handlers forDomainError, validation errors, and a catch-all emitapplication/problem+json(RFC 9457). They are the only place exceptions become status codes. TheRequestValidationErrorhandler returns422for body errors and400for query, path, and header errors (loc[0]). FastAPI ignores unknown query parameters: reject them with a query model set toextra="forbid", and clamp an oversizepage_sizein code rather than rejecting it withQuery(le=...).async deffor awaitable I/O and for handlers that do no I/O at all; plaindef(FastAPI runs it in a threadpool) when the work blocks. Unsure: plaindef.BackgroundTasksonly for short, fire-and-forget, failure-tolerant work (emails, cache warm). Anything retryable, long, or business-critical goes to a real queue/worker.- Startup/shutdown via the lifespan context manager.
- Middleware for request ID, timing, the error boundary, and
Idempotency-Keyreplay (only middleware sees the final status, headers, and body to store), never business rules. The catch-allExceptionhandler runs outside all middleware, so replay middleware records an unhandled error's500problem itself.
11. Async
- Nothing blocking in
async def(time.sleep,requests, sync DB drivers, heavy file I/O): useasyncio.sleep,httpx.AsyncClient, async drivers (asyncpg), orawait asyncio.to_thread(...); CPU-bound work goes to aProcessPoolExecutoror a worker. - One stack per project: sync SQLAlchemy with sync routes, or
AsyncSessionwith async routes. - Concurrency via
asyncio.TaskGroup;gather(..., return_exceptions=True)only when deliberately handling partial failure. - Never a bare
asyncio.create_task: keep a reference, await it, or use a TaskGroup, or it can be garbage-collected and its exception vanishes. - Every outbound call gets a timeout (
asyncio.timeout()or the client's). Onasyncio.CancelledError, clean up and re-raise; never swallow it. - Reuse one
AsyncClient/pool for the app lifetime. - Request-scoped context lives in
ContextVars, never globals.
12. Performance
- Partial selects on wide tables (
select(Order.id, Order.total)) only on read paths feeding a response schema; never mutate through one: writes go through a fully loaded aggregate. - Bulk operations for volume:
insert().values([...]),session.execute(insert(Model), rows),session.execute(update(...)),COPYfor very large loads. - Stream large results (
yield_per()/session.stream(),StreamingResponsefor exports); never.all()an unbounded table. - Every cache has an explicit key, TTL, and invalidation story:
functools.cache/lru_cachefor pure in-process functions, Redis for shared/cross-process. Never cache per-user data under a global key. - Optimize only with a measurement (
cProfile,EXPLAIN ANALYZE, timing logs), and state the numbers in the PR.
13. Testing
- pytest only.
tests/mirrorsapp/; filestest_<module>.py; teststest_<unit>_<scenario>_<expected>()(test_reserve_inventory_when_out_of_stock_raises). - Unit tests for services/domain: no DB, no network; fake repositories through their Protocols.
- Integration tests for repositories and routes: a real database (testcontainers or a disposable schema), transaction-rollback fixtures for isolation,
TestClient/httpx.ASGITransportfor the app. Migration tests run on their own empty database:CONCURRENTLYcannot run inside a fixture's transaction. - Mock at the boundary you own (repository, client interface), not deep internals; prefer fakes over
MagicMockfor anything with behaviour;respx/responsesfor HTTP; never hit real third parties. - Cover empty/one/many, boundary values,
None/missing, duplicates, unicode,Decimalrounding, timezone/DST, concurrent update, permission denied, upstream timeout, and every raised exception path. - Tests are deterministic (injected clock or
freezegun, seeded randomness, nosleep, no ordering dependence, no shared mutable module state), and every bug fix ships a regression test that fails before the fix. pytest.mark.parametrizeover copy-pasted cases; factories/builders (factory_boyor plain helpers) over giant literal fixtures.- Register every custom marker (
slow,integration) in[tool.pytest.ini_options] markers = [...]with strict marker validation on. - Coverage ≥ 85% overall, ~100% on services/domain.
14. Code Quality Gates
All pass locally and in CI before code is complete:
ruff format . # local (or: black .); CI: ruff format --check .
ruff check --fix . # local only
ruff check . # CI: no --fix; it rewrites the checkout and exits 0
mypy --strict app
pytest --cov=app --cov-fail-under=85 -q # --cov* come from pytest-cov; declare that dependency
pip-audit
alembic upgrade head- In a repo not yet clean under these tools, fix lint and type findings only in lines you touch and format only those lines (
ruff format --range, one file per call); a whole-file cleanup is its own commit and PR. - Ruff rules:
E,F,I,N,UP,B,S,SIM,C4,RET,ARG,PTH,ASYNC,ANN, optionally plusC90with[tool.ruff.lint.mccabe] max-complexity = 8. NarrowEtoE4,E7,E9or addE111,E114,E117,W191,E501tolint.ignore; those codes conflict with the formatter.Sflags every pytestassert(S101): add[tool.ruff.lint.per-file-ignores] "tests/**" = ["S101"]. - Config lives in
pyproject.toml:[tool.mypy] strict = true; line length 100 set explicitly under[tool.ruff]/[tool.black], or the tools silently enforce 88. Formatters do not reflow comments or docstrings; keep those narrower than code by hand. - Pin the ruff, black, and mypy versions in
pyproject.toml(the flag set behind--strictchanges between mypy releases) and lock dependencies with a lockfile. - Zero warnings (
filterwarnings = ["error"]under[tool.pytest.ini_options]), zero skipped tests. Every new# noqa/# type: ignorenames its code (# type: ignore[arg-type]) and carries a reason comment. A failing gate is not "unrelated" until proven so.
15. Documentation
- Docstrings on every public module, class, function, and method, including
__init__: a one-line summary in the imperative mood ("Return", not "Returns"), thenArgs:/Returns:(orYields:)/Raises:. Sections may be omitted where the name and signature are informative enough; a trivial function may skip the docstring. Raises:lists only the exceptions in the function's contract: theValueErrorfrom an argument precondition stays out.- Docstrings state the contract and why, never the signature or the types.
- Inline comments only for non-obvious rationale (a business rule, a workaround with a link, a deliberate perf trade-off). Delete commented-out code; every TODO names an owner or ticket.
- Adding a setup step, env var, command, or service updates the README/
docs/; new env vars go in.env.examplein the same change. - FastAPI routes carry
summary,description,responses={...}(4xx/5xx declared asapplication/problem+jsonundercontent, sincemodel=files them underapplication/json; FastAPI keeps its default422schema unless422or4XXis declared), and schemaField(examples=...); exportapp.openapi()to the committed spec file the contract gates diff. - Record non-obvious architectural decisions as a short ADR in
docs/adr/.
16. Agent Rules
- Never invent business rules: if credit limits, tax treatment, rounding, statuses, or SLAs are ambiguous, ask; do not silently pick a default.
- Never break a public Python API (signature, default, return type, import path) to apply a rule here (one class per file, keyword-only booleans, raise-not-sentinel): keep a re-export or deprecation shim and say so.
- Add no dependency without saying why and confirming; prefer the stdlib.
- Flag anything security-relevant you touch (auth, tenancy, input handling, SQL, file paths, outbound URLs) in the summary.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

