Dataclass Slots And Frozen Block State Drift

slots=True, frozen=True, and kw_only=True turn a dataclass into an immutable config record: keyword-only construction and no per-instance __dict__.

PythonConfig Management

Code

pythonsnippet
28 lines
from dataclasses import FrozenInstanceError, dataclass


@dataclass(slots=True, frozen=True, kw_only=True)
class WebhookConfig:
    url_path: str
    secret: str
    retries: int = 3


cfg = WebhookConfig(url_path="/hooks/deploy", secret="s3cr3t")
print(cfg)
print("slots:", WebhookConfig.__slots__)

# kw_only:位置参数被直接拒绝,字段含义不会错位
try:
    WebhookConfig("/hooks/deploy", "s3cr3t")
except TypeError as exc:
    print("positional args rejected:", exc)

# frozen:任何就地修改都会抛 FrozenInstanceError
try:
    cfg.retries = 5
except FrozenInstanceError as exc:
    print("frozen blocks writes:", exc)

# slots:字段存在类描述符里,实例不再挂 __dict__
print("instance has __dict__:", hasattr(cfg, "__dict__"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

WebhookConfig(url_path='/hooks/deploy', secret='s3cr3t', retries=3)
slots: ('url_path', 'secret', 'retries')
positional args rejected: WebhookConfig.__init__() takes 1 positional argument but 3 were given
frozen blocks writes: cannot assign to field 'retries'
instance has __dict__: False

How the snippet works

Dataclass Slots And Frozen Block State Drift comes down to the class WebhookConfig.

The demo data lives in module-level bindings: cfg.

Using it

Running the file prints labeled results such as slots:, positional args rejected:, frozen blocks writes: — each operation’s effect is visible in the output.

Key statements

except FrozenInstanceError as exc:
    print("frozen blocks writes:", exc)
except TypeError as exc:
    print("positional args rejected:", exc)

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Every import resolves inside the standard library — `dataclasses`. Its state lives in module-level bindings: `cfg`.