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__.
Code
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__: FalseHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.