python

A set of coding rules for Python, a general-purpose programming language. It covers type hints, file handling, data models, imports, tests with pytest, and error handling.

In plain words
What is it for?
Use it when writing or reviewing Python functions, classes, file-processing code, data containers, exceptions, imports, and pytest tests.
Why use it?
It reduces unclear types, fragile file operations, deeply nested code, and errors that are hidden or handled too broadly.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/nedcodes-ok/cursorrules-collection/python
Clone the repo
git clone --depth 1 https://github.com/nedcodes-ok/cursorrules-collection
Per session 643 This file is loaded in full into every session.
When invoked 643 The same file — it is already loaded in full.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00643 $0.00643
Opus 5 $0.00321 $0.00321
Sonnet 5 $0.00129 $0.00129
Haiku 4.5 $0.00064 $0.00064

Measured yesterday against content hash d51f9f11306c, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

python scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

Origin

Copies of this mod

1 near-identical copy found in the catalogue:

  • python — 100% identical, 0 lines differ
rules-mdc/languages/python.mdc · 57 lines

How it starts

The opening of the file, as written. The whole thing — 57 lines — stays where its author put it; the contents beside it link to each section on GitHub.

Python Rules

Style & Structure

  • Use type hints for all function signatures, return types, and class attributes
  • Prefer f-strings over .format() or % formatting
  • Use pathlib instead of os.path for all file operations
  • Prefer list/dict/set comprehensions over map/filter when the expression fits one line
  • Use dataclasses for plain data containers. Pydantic BaseModel for validated/serialized data
  • Use Enum for fixed sets of values, StrEnum for string enums (Python 3.11+)
  • Use __slots__ on data-heavy classes to reduce memory
  • Prefer collections.abc types for type hints: Sequence, Mapping, Iterable over concrete types

Error Handling

  • Use specific exception types, never bare except: or except Exception:
  • Use contextlib.suppress() for expected, recoverable exceptions
  • Return early to avoid deep nesting. Max 3 levels of indentation
  • Custom exceptions inherit from a project-level base exception
  • Never silence exceptions in production. Log at minimum
  • Use else clause on try/except for code that should run only when no exception occurred

Imports

  • Group imports: stdlib, third-party, local (separated by blank lines)
  • Use absolute imports over relative imports
  • Never use wildcard imports (from x import *)
  • Sort with isort or ruff. One import per line for third-party packages
  • Lazy imports for heavy dependencies only needed in specific code paths

Functions & Classes

  • Keep functions under 30 lines. Extract helpers aggressively
  • Use *args and **kwargs sparingly. Document types when used
  • Prefer returning values over modifying mutable arguments
  • Use generators (yield) for large sequences instead of building full lists
  • Keyword-only arguments after * for functions with 3+ params
  • Use @staticmethod only when the method truly needs no instance/class access
  • Prefer composition over inheritance. Use protocols (typing.Protocol) for interfaces
  • Use @property for computed attributes, not for hiding method calls

Testing

  • Use pytest over unittest. No test classes unless sharing fixtures
  • Name tests: test_<function>_<scenario>_<expected>
  • Use fixtures for shared setup, @pytest.mark.parametrize for multiple cases
  • Use tmp_path fixture for file operations, not manual temp directories
  • Mock at boundaries (HTTP, DB, filesystem), not internal functions
  • Use pytest.raises(ExactError, match="message") for exception testing

Read the full file on GitHub · 57 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 57 lines · 643 tokens per session scan A d51f9f11306c

Subscribe to this mod's changes

python is a cursor rule published in the GitHub repository nedcodes-ok/cursorrules-collection (37 stars, last pushed 6mo ago), licensed MIT. It adds 643 tokens to every session, about $0.0032 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.