python-dataclass-architect
Design high-performance, memory-efficient, type-safe Python data structures utilizing slots=True, frozen=True, __post_init__ validation, and slotted inheritance. Do not use for mutable state dictionaries or untyped data objects.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- python-dataclass-architect
- description
- Design high-performance, memory-efficient, type-safe Python data structures utilizing slots=True, frozen=True, __post_init__ validation, and slotted inheritance. Do not use for mutable state dictionaries or untyped data objects.
02 资源文件 2
- 参考文档CARD.md3.9 KB
- 参考文档config.default.yaml302 B
03 SKILL.md 正文
Python Dataclass Architect
python-dataclass-architect is the structural design and memory optimization engine for Python @dataclass entity models. It eliminates boilerplate, enforces object immutability, reduces memory overhead by ~75% via slots=True, validates domain invariants in __post_init__, isolates derived fields, and guarantees slot integrity across inheritance hierarchies.
Every dataclass architecture session executes this five-stage progression:
[1. Immutability & Hashability Assessment] → [2. Memory Footprint Profiling & Slotting] → [3. Container Isolation & Default Factories] → [4. Invariant Validation & Derived Fields] → [5. Hierarchy Integrity & Representation Tuning]
See CARD.md for the companion summary card, memory benchmarks, and verification invariants.
Consult /codebase-design for deep module design principles and /data-topology-mapper for state topologies.
1. Immutability & Hashability Assessment
Determine whether the data structure represents an immutable Value Object or a mutable Entity:
- Value Objects (Immutable):
- Apply
@dataclass(frozen=True)when the object represents a discrete value that must not change after construction (e.g. coordinates, route segments, configuration snapshots). - Mechanics: Generates immutable
__setattr__and__delattr__methods that raiseFrozenInstanceErrorupon modification attempts. - Automatic Hashability: Frozen dataclasses automatically generate a compatible
__hash__()based on equality fields, allowing them to serve as dictionary keys and set members.
- Apply
- Entities (Mutable):
- Use standard dataclasses only when state mutations during object lifecycle are explicitly required by domain logic.
from dataclasses import dataclass
@dataclass(frozen=True)
class RouteSegment:
from_hub: str
to_hub: str
distance_km: float
carrier: str
Completion criterion: Mutability profile explicitly decided, with
frozen=Trueand automatic__hash__()applied to all Value Objects.
2. Memory Footprint Profiling & Slotting
Eliminate per-instance dictionary overhead in data processing and high-volume systems:
┌─────────────────────────────────────────────────────────────┐
│ PYTHON OBJECT MEMORY ALLOCATION │
├──────────────────────────────┬──────────────────────────────┤
│ Standard Dataclass │ Slotted Dataclass │
│ - Uses instance __dict__ │ - Uses __slots__ descriptor │
│ - ~296 bytes overhead │ - ~72 bytes overhead │
│ - Dynamic attribute adding │ - Fixed, fast attribute slots│
└──────────────────────────────┴──────────────────────────────┘
- Enable Slot Optimization:
- Apply
@dataclass(slots=True)(Python ≥ 3.10) for high-volume classes, ETL pipelines, or large collections in memory.
- Apply
- Quantify Memory Savings:
- Standard instance:
sys.getsizeof(instance.__dict__)overhead (~296 bytes per object before data). - Slotted instance: ~72 bytes total object descriptor footprint, saving ~75% overhead per object.
- Standard instance:
- Combination:
- Combine with immutability when optimal:
@dataclass(slots=True, frozen=True).
- Combine with immutability when optimal:
Completion criterion:
slots=Truedeclared on high-volume and domain entity models, eliminating__dict__overhead.
3. Container Isolation & Default Factories
Prevent the classic shared mutable default argument vulnerability:
- Mandatory
default_factoryfor Mutable Containers:- Never assign mutable literals (
list,dict,set) directly as default values:items: list[str] = [](forbidden). - Always use
field(default_factory=list)orfield(default_factory=dict)to guarantee that every instance receives its own isolated collection.
- Never assign mutable literals (
- Dynamic Value Initialization:
- For timestamps, UUIDs, or dynamic defaults, use
field(default_factory=datetime.utcnow)orfield(default_factory=uuid.uuid4).
- For timestamps, UUIDs, or dynamic defaults, use
from dataclasses import dataclass, field
from datetime import datetime
import uuid
@dataclass(slots=True)
class OrderBatch:
batch_id: str = field(default_factory=lambda: str(uuid.uuid4()))
items: list[str] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.utcnow)
Completion criterion: All mutable containers and dynamic defaults encapsulated via
default_factory, preventing cross-instance reference sharing.
4. Invariant Validation & Derived Fields
Enforce structural correctness at construction time and encapsulate calculated state:
- Encapsulate Derived Fields with
init=False:- When a field is computed from other inputs, declare
field(init=False)to prevent callers from supplying erroneous manual values.
- When a field is computed from other inputs, declare
- Execute
__post_init__Assertions:- Validate numerical bounds, string formats, and business constraints inside
__post_init__(). - Raise explicit
ValueErrororTypeErroron invalid states. - Compute and assign the derived fields.
- Validate numerical bounds, string formats, and business constraints inside
- Handling
frozen=Truein__post_init__:- If computing derived fields on a frozen dataclass, use
object.__setattr__(self, 'derived_field', computed_value).
- If computing derived fields on a frozen dataclass, use
@dataclass(slots=True)
class Shipment:
tracking_id: str
weight_kg: float
priority: str = "standard"
freight_cost: float = field(init=False)
def __post_init__(self) -> None:
if self.weight_kg <= 0:
raise ValueError(f"weight_kg must be positive, got {self.weight_kg}")
rates = {"standard": 1.85, "express": 3.40}
if self.priority not in rates:
raise ValueError(f"Invalid priority: {self.priority!r}")
self.freight_cost = round(self.weight_kg * rates[self.priority], 2)
Completion criterion:
__post_init__validation enforced; derived state isolated withfield(init=False)and calculated automatically.
5. Hierarchy Integrity & Representation Tuning
Ensure safe inheritance and tune object serialization and representation:
- Enforce Slotted Inheritance Chain:
- In Python, if a subclass uses
slots=True, all parent classes up the inheritance tree must also useslots=True(or explicitly define__slots__). Mixing slotted and non-slotted classes breaks memory optimization or throws attribute errors.
- In Python, if a subclass uses
- Exclude Private State from Repr and Equality:
- Use
field(repr=False, compare=False)for internal caches, lock instances, or private audit tags (_audit_tag).
- Use
- Ecosystem Deserialization Bridges:
- Use
dacite.from_dict()for nested dictionary-to-dataclass hydration without manual parsing. - Use
marshmallow-dataclassfor automatic schema generation. - Upgrade to
pydantic.dataclasses.dataclasswhen external JSON API payload validation is required.
- Use
Completion criterion: Inheritance chains uniformly slotted; internal fields hidden from
reprandcompare; serialization bridge verified.
In-File Reference: Production-Grade Dataclass Template
from dataclasses import dataclass, field
from datetime import datetime
import uuid
@dataclass(slots=True, frozen=True)
class TransactionRecord:
account_id: str
amount_cents: int
currency: str = "USD"
transaction_id: str = field(default_factory=lambda: str(uuid.uuid4()))
timestamp: datetime = field(default_factory=datetime.utcnow)
tags: list[str] = field(default_factory=list)
fee_cents: int = field(init=False)
_audit_hash: str = field(default="", repr=False, compare=False)
def __post_init__(self) -> None:
if self.amount_cents <= 0:
raise ValueError(f"amount_cents must be positive, got {self.amount_cents}")
fee = int(self.amount_cents * 0.02)
object.__setattr__(self, "fee_cents", fee)
object.__setattr__(self, "_audit_hash", f"{self.transaction_id}:{fee}")
The Three Foundational Pillars
1. The Visual Brief
Synthesize findings, structural matrices, and execution DAGs into a self-contained HTML visual brief written to %TEMP%\python-dataclass-architect-<timestamp>.html (or /tmp/python-dataclass-architect-<timestamp>.html on Unix) loading Tailwind CSS and Mermaid.js via CDN. Present the absolute clickable path to the user for visual review.
2. The Mandatory Checkpoint
When proposing structural modifications, refactors, or execution pipelines, always author an implementation_plan.md artifact with RequestFeedback: true. The agent must STOP and wait for explicit human confirmation before executing mutating actions.
3. Explicit Anti-Patterns
Rigid behavioral boundaries must be maintained to prevent catastrophic failure modes.
Anti-Patterns
- Mutable Default Values — Setting
items: list = []directly, leading to shared state across all instances of the class. - Unslotted High-Volume Entities — Creating millions of dataclass instances without
slots=True, wasting hundreds of megabytes in__dict__overhead. - Slotted-Unslotted Hierarchy Collision — Inheriting a
slots=Trueclass from an unslotted base class, leading to subtle__dict__reappearance or attribute crashes. - Caller-Exposed Derived Fields — Leaving computed fields in the
__init__signature instead of declaringfield(init=False), allowing callers to pass conflicting derived values. - Post-Init Frozen Mutation without Object Setattr — Attempting direct assignment
self.cost = xinside__post_init__on afrozen=Truedataclass, raisingFrozenInstanceError.
04 同仓库更多 Skills
ui-behavior-primitive-architect
Architect, audit, and verify zero-dependency headless UI behavior primitives, WebMCP agent bridges, WAI-ARIA/SSR/RTL tri-modal checks, and framework expert routing. Do not use for static CSS theme styling or backend database migrations.
trustgraph-ontology-governor
Govern knowledge graphs, SHACL-AF triple policies, OntologyRAG subclass validation, PROV-O dual named graphs, and Laya entropy decision scoring. Do not use for relational SQL queries or generic web scraping.
shim-harness-governor
Govern universal CLI agent loops, 4-tier tool permissions, ancestor-symlink workspace sandboxes, deterministic-first command routing, collision-safe MCP namespacing, and layered skill loading. Do not use for static UI styling or external SQL analytics.
graphiti-zep-memory-governor
Govern bi-temporal knowledge graphs with Graphiti future-edge clamping, MinHash/LSH entity dedup, RRF/MMR reranking, and Zep typed ontologies. Do not use for static SQL joins or generic web crawling.
agora-mcp-workbench-architect
Architect, audit, and orchestrate Agora Workbench MCP servers, loopback sidecars, unified state graphs, gateway/dispatcher connectors, and policy-enforced data lakes. Do not use for static frontend CSS styling or non-MCP desktop GUI automation.
skill-eval-assurance-runner
Evaluate and assure agent skills using small-N Wilson confidence intervals, unbiased pass^k reliability, deterministic trajectory graders, preflight boundary honesty, and sealed digest verification. Do not use for subjective prose review or unconstrained production deployment.