writing-dataclasses
Skill721 starsChanged 59 days agoMITView on GitHub
House rules for Python dataclasses in PostHog: when to reach for one instead of a tuple or `dict[str, Any]`, which decorator to use (`@frozen` from `posthog.dataclasses`), how to name, construct, consume and evolve them, how to keep secrets out of `repr`, and when a function should accept a dataclass instead of its unpacked fields. Use when adding or changing a dataclass, returning or passing several values from a function, converting a tuple or dict payload, deciding `frozen=`/`slots=`/`kw_only=`, or passing a facade contract DTO through internal layers. Not for pydantic models used as HogQL/query schema, DRF serializers, or Django models.
1 other project uses a version of this.
Adopted by
Most recently taken up by
- PostHog/posthogword for word, first seen Oct 4, 2026
Other versions1 project uses a version of this.
Word for word · 1
- PostHog/posthog★ 40k100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
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 repository119 other files it gives its agents.
- AGENTS.mdAGENTS.md
- common/AGENTS.mdAGENTS.md
- proto/AGENTS.mdAGENTS.md
- rust/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- common/CLAUDE.mdCLAUDE.md
- proto/CLAUDE.mdCLAUDE.md
- rust/CLAUDE.mdCLAUDE.md
- .cursor/rules/django-python.mdcCursor rule
- .cursor/rules/react-typescript.mdcCursor rule
- .cursor/rules/rust.mdcCursor rule
- adding-activity-loggingSkill
- adding-api-scopesSkill
- adding-inbound-webhooksSkill
- adding-inbox-sourcesSkill
- adding-ingestion-warningsSkill
- adding-mcp-store-serversSkill
- adding-personhog-rpcSkill
- adding-product-alertingSkill
- adding-project-secret-api-key-authSkill
- adopting-generated-api-typesSkill
- analyzing-experiment-precompute-canarySkill
- analyzing-experiment-query-performanceSkill
- analyzing-insights-across-teamsSkill
- announcing-behavior-changesSkill
- auditing-llm-gateway-paritySkill
- auditing-warehouse-source-coverageSkill
- authenticating-to-clickhouseSkill
- authoring-ci-workflowsSkill
- autoresolving-pr-conflictsSkill
- building-product-empty-statesSkill
- clickhouse-migrationsSkill
- debugging-ci-failuresSkill
- debugging-local-replaySkill
- debugging-local-task-agent-runsSkill
- debugging-mcp-analyticsSkill
- debugging-signals-pipelineSkill
- debugging-table-access-deniedSkill
- depot-ciSkill
- depot-container-buildsSkill
- depot-github-runnersSkill
- developing-subscriptionsSkill
- django-migrationsSkill
- django-startup-timeSkill
- documenting-warehouse-sourcesSkill
- editing-agents-mdSkill
- establishing-code-ownershipSkill
- extending-hobby-smoke-testsSkill
- extending-personhog-test-harnessSkill
- finding-llm-gateway-migration-candidatesSkill
- fixing-flaky-testsSkill
- gating-production-deploysSkill
- gating-sensitive-actionsSkill
- generating-clickhouse-query-performance-reportsSkill
- hogliSkill
- implementing-mcp-toolsSkill
- implementing-mcp-ui-appsSkill
- implementing-warehouse-sourcesSkill
- improving-drf-endpointsSkill
- improving-mcp-toolsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
6 rules. About 0 are common, 1 is distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
Return or pass a dataclass instead of a tuple: when two or more elements share a type ((start, end), (width, height), (rows, columns)), or …
- Very specific: line 16
Prefer a dataclass over
dict[str, Any]: when a fixed set of values crosses a function boundary. - Very specific: line 21
Use @frozen from posthog.dataclasses for internal value and result objects.
- Very specific: line 41
Don't add frozen=False to a bare @dataclass you didn't otherwise touch.
- Very specific: line 56
Read fields with dot notation (result.start).
- Distinctive: line 66
When a function's parameters mirror the fields of a dataclass the caller already holds, accept the dataclass instead of the unpacked fields.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Writing dataclasses
The point of every rule here is the same: values that share a type get swapped silently, and a positional tuple or a dict[str, Any] lets that happen. A named, frozen dataclass makes the swap a typecheck failure instead of a runtime bug. Everything below follows from that; if a rule doesn't serve it in your case, say so in the PR and skip it.
When a dataclass, when not
- Return or pass a dataclass instead of a tuple when two or more elements share a type (
(start, end),(width, height),(rows, columns)), or when the tuple has roughly 3+ elements and positional access hurts readability. A small tuple of clearly different types ((user, count)) is fine as-is. - Prefer a dataclass over
dict[str, Any]when a fixed set of values crosses a function boundary. A dict key typo fails at runtime; a dataclass field typo fails typecheck. Dicts stay for genuinely dynamic key sets. NamedTupleis not the answer for the swap problem: it still unpacks positionally.
Which decorator
Use @frozen from posthog.dataclasses for internal value and result objects. It is @dataclass with frozen=True, kw_only=True, slots=True as defaults, and every flag is overridable:
from posthog.dataclasses import frozen
@frozen
class BillingPeriod:
start: datetime
end: datetime
@frozen(slots=False) # class uses functools.cached_property
class ParsedQuery: ...
@frozen(frozen=False) # genuinely mutated after construction (a builder, an accumulator)
class RunAccumulator: ...kw_only=Trueis what actually prevents swaps at construction:BillingPeriod(start=a, end=b), neverBillingPeriod(a, b). Don't override it without a reason.slots=Trueblocksfunctools.cached_propertyand ad-hoc attributes; override withslots=Falserather than dropping@frozen.- A bare
@dataclasswith no explicitfrozen=fails the ratchet inposthog/test/repo_invariants/test_dataclass_defaults.pyand is flagged by the advisoryprefer-frozen-dataclassessemgrep rule.@dataclass(frozen=False)passes; the ratchet asks for a stated choice, not immutability. If you only moved an existing bare@dataclass, regenerate the baseline withpython posthog/test/repo_invariants/test_dataclass_defaults.pyinstead of decorating it. - Don't add
frozen=Falseto a bare@dataclassyou didn't otherwise touch. The ratchet counts per file against a baseline; an unchanged count passes, and the edit is churn in someone else's file. - Facade contracts (
products/<name>/backend/facade/contracts.py) are frozen dataclasses too, usuallypydantic.dataclasses.dataclass(frozen=True)so they validate on construction. See products/architecture.md.
Naming
Name the class after the domain concept, not the plumbing: ClickHouseCredentials, BillingPeriod, SnapshotManifestItem. *Result only when the function's outcome genuinely is the concept; never *Info, *Data, *Tuple, *Response for an internal object. Underscore-prefix classes private to one module.
Constructing and enforcing invariants
- Enforce invariants in
__post_init__(start <= end, exactly one auth method set, value in range) so an invalid instance fails at construction rather than deep in later logic. On a frozen class useobject.__setattr__only if you must normalize; prefer raising. - Type a field holding a closed set of strings as
Literal[...]or an enum, not barestr. Check call sites: narrowing an existing field can surface mypy errors where callers pass a plainstr; fix the callers, don't widen the field back. - A frozen dataclass hashes, so use a small keyed class as a dict or set key instead of a tuple when the key has two or more same-typed parts.
Consuming and evolving
- Read fields with dot notation (
result.start). Nevera, b = result.a, result.binto positional locals; that reintroduces the swap. - Evolve a frozen instance with
dataclasses.replace(instance, field=value), not by copying fields by hand. - Dispatch on variants with
match/case(case BinaryOp(left=left, right=right):) when there are several; a single-type check stays a plainisinstanceguard.
Secrets
Mark secret fields with field(repr=False) so they cannot leak through repr() into tracebacks and logs, and never asdict() such a dataclass into log output, which reintroduces what repr=False hides.
Passing a dataclass through layers
When a function's parameters mirror the fields of a dataclass the caller already holds, accept the dataclass instead of the unpacked fields. That stops same-typed positionals being threaded through several layers, and it is Fowler's Preserve Whole Object.
Three carve-outs, in priority order:
- Invariants win over mirroring. Never pass a wider type into a callee that needs a narrower one. If the dataclass has
url: str | Noneand the helper needs astr, keep thestrparameter (or narrow the type at the boundary); do not accept the dataclass and add a runtimeValueError. That trades a typecheck for a guard clause, which is the opposite of the point. - Wire signatures keep their shape. Temporal
@activity.defn/@workflow.runand celery task boundaries take what they take; the helper behind them accepts the dataclass. - Facade contracts that are also request bodies are wire signatures too. A contract in
facade/contracts.pybacked byDataclassSerializerand@validated_requestis the HTTP body, the OpenAPI schema, and the shape shipped clients send. A product'slogicmay accept its own contract while the fields are one-to-one with what logic needs; do not pre-emptively build a parallel internal DTO. Split into an internal parameter object at the first real divergence: the wire carries dead or deprecated fields logic ignores, logic needs values the wire must not accept, or logic needs an invariant the wire can't promise. The split lives infacade/api.py, the only in-process caller.
What enforces this
posthog/test/repo_invariants/test_dataclass_defaults.py(blocking ratchet): new bare@dataclasswithoutfrozen=..semgrep/rules/devex/prefer-frozen-dataclasses.yamlandtuple-return-prefer-dataclass.yaml(advisory).- Everything else is review.
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.

