agentleFS
iyazerskiiyazerski/dev-flows-plugin/skills/python-best-practices/SKILL.md

python-best-practices

Skill0 starsChanged 5 months agoMITView on GitHub

Python rules that ruff and ty can't enforce, including FastAPI, SQLAlchemy, and dataframe code. Use when writing, reviewing, refactoring, or debugging Python code.

20 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use react-best-practices, typescript-best-practices and 3 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.
  • OpenAISkill

    react-best-practices

    React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.

    Also in 3 projects that use this

  • jaydubya818Skill

    typescript-best-practices

    Use when TypeScript needs focused type-safety, API, or error-handling guidance.

    Also in 3 projects that use this

  • BlockSkill

    frontend-design

    Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

    Also in 4 projects that use this

  • SentrySkill

    skill-creator

    Create new agent skills following the Agent Skills specification. Use when asked to "create a skill", "add a new skill", "write a skill", "make a skill", "build a skill", or scaffold a new skill with SKILL.md. Guides through requirements, writing, registration, and verification.

    Also in 4 projects that use this

  • GoogleSkill

    tdd

    Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.

    Also in 3 projects that use this

The file

Show its rules and text

We split this skill into the rules it gives an agent

19 rules. 0 are common, 5 are distinctive, and 14 are very specific to this project.

  • 0

    Common

    Most of the 16 edited versions we read keep these.

  • 5

    Distinctive

    This author's own choices. Worth a look.

  • 14

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Read the matching reference before you change code that uses:

    line 13
  2. Very specific:

    Run Python and its tools with uv run, and add dependencies with uv add.

    line 21
  3. Distinctive:

    Write code that passes the asset config even when the repo's config is weaker.

    line 22
  4. Very specific:

    Don't re-check what types or models already guarantee: no redundant isinstance (narrowing a union is fine), no hasattr or getattr(obj, …

    line 30
  5. Very specific:

    Use Literal or StrEnum for fixed string sets, and an enum instead of mutually exclusive bool flags.

    line 37
  6. Very specific:

    Don't add an ABC or Protocol for a single implementation.

    line 39
  7. Very specific:

    Use Pydantic v2 (model_validate, model_dump, field_validator, ConfigDict).

    line 44
  8. Very specific:

    Use Model.model_validate_json(raw) instead of json.loads + validation, and TypeAdapter(list[Item]) instead of a wrapper model (validate …

    line 47
  9. Very specific:

    Use model_validate(obj, from_attributes=True) instead of hand-written to_dict / from_row mappers for matching fields.

    line 50
  10. Distinctive:

    Use plain dataclasses for internal values never parsed from outside.

    line 53
  11. Very specific:

    Never turn unexpected failures into values (except ...: return None, {}, [], or False).

    line 59
  12. Very specific:

    Don't pre-check what the callee checks (like path.exists() before open()).

    line 61
  13. Very specific:

    Prefer module-level functions over static-only classes or stateless single-method classes.

    line 69
  14. Distinctive:

    Keep no state in module globals, and build clients/connections at startup rather than import time.

    line 72
  15. Very specific:

    Never block the event loop in async def.

    line 77
  16. Very specific:

    Start tasks in asyncio.TaskGroup, use asyncio.timeout() for deadlines, and bound fan-out with a Semaphore or worker pool instead of …

    line 81
  17. Very specific:

    Test through public entry points (TestClient / ASGITransport, CLI, service functions) against a real test database (in-memory SQLite or …

    line 86
  18. Very specific:

    Avoid bare MagicMock() (it hides renames).

    line 89
  19. Distinctive:

    Don't test the framework (e.g., Pydantic rejecting a missing field).

    line 90

“Common” is measured: kept by at least 6 in 10 of the 16 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Python best practices

This file assumes uv and repo hooks that run ruff check, ruff format, ty check, and pytest. It lists only what those tools don't catch. If the repo has no Python hooks, suggest that the user adopt assets/pre-commit-config.yaml and the settings in assets/pyproject.toml.

Read the matching reference before you change code that uses:

  • FastAPI: references/fastapi.md
  • SQLAlchemy: references/sqlalchemy.md
  • pandas, Polars, PyArrow, or large files and query results: references/dataframes.md

Tools

  • Run Python and its tools with uv run, and add dependencies with uv add.
  • Write code that passes the asset config even when the repo's config is weaker.
  • Fix a lint instead of silencing it. If a rule is wrong for one line, use # noqa: CODE or # ty: ignore[rule] with a reason. Never silence a type error with cast, Any, or # type: ignore; fix the model or signature, or wrap an untyped library once in a typed function.

Trust the types

  • Don't re-check what types or models already guarantee: no redundant isinstance (narrowing a union is fine), no hasattr or getattr(obj, "field", default) on known classes, no is not None on non-optional values, and no .get(key, default) on validated data. If the type is wrong, fix the type.
  • Make a parameter optional only when a real caller passes None or omits it.
  • Parse untrusted data once at the boundary (requests, files, env, queues, third-party responses) and pass typed models inward, never dict[str, Any] or raw JSON.
  • Use Literal or StrEnum for fixed string sets, and an enum instead of mutually exclusive bool flags.
  • Don't add an ABC or Protocol for a single implementation. Add one when a second implementation or test fake needs it, in the consuming module.

Pydantic

  • Use Pydantic v2 (model_validate, model_dump, field_validator, ConfigDict).
  • Let the model parse and convert (dates, UUID, Decimal, enums, Field/Annotated constraints) instead of pre-converting strings or validating after construction.
  • Use Model.model_validate_json(raw) instead of json.loads + validation, and TypeAdapter(list[Item]) instead of a wrapper model (validate item by item when bad items must be skipped or reported).
  • Use model_validate(obj, from_attributes=True) instead of hand-written to_dict / from_row mappers for matching fields.
  • Load settings once with pydantic-settings and pass them in; avoid scattered os.getenv.
  • Use plain dataclasses for internal values never parsed from outside.

Errors

  • Catch only what you can handle around the smallest failing block; let the rest reach the boundary to be logged once.
  • Never turn unexpected failures into values (except ...: return None, {}, [], or False). Returning None for an expected "not found" is fine.
  • Don't pre-check what the callee checks (like path.exists() before open()).
  • Raise a small set of domain exceptions from business logic and map them to HTTP or exit codes at the boundary.
  • Broad except Exception belongs only in a background loop that must survive one bad item (log with logger.exception and continue).

Structure

  • Prefer module-level functions over static-only classes or stateless single-method classes. Put code in its owning module, not utils.py or helpers.py, and delete pass-through wrappers.
  • Keep no state in module globals, and build clients/connections at startup rather than import time.

Async

  • Never block the event loop in async def. Ruff catches requests, open, and time.sleep, but not sync DB sessions, sync SDK clients, or CPU work; use async clients, asyncio.to_thread, or plain def FastAPI routes/dependencies (a sync helper called from async def still blocks).
  • Start tasks in asyncio.TaskGroup, use asyncio.timeout() for deadlines, and bound fan-out with a Semaphore or worker pool instead of unbounded gather.

Tests

  • Test through public entry points (TestClient / ASGITransport, CLI, service functions) against a real test database (in-memory SQLite or test Postgres), mocking only external services (e.g., MockTransport).
  • Avoid bare MagicMock() (it hides renames); use a fake or create_autospec.
  • Don't test the framework (e.g., Pydantic rejecting a missing field).

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.