How can an immutable experiment configuration produce a one-parameter variant?
dataclasses.replace builds a new instance of the same type using existing fields and requested changes through initialization.
Python example and interpretation
A baseline batch size of eight stays available while its variant uses sixteen. Mutable objects inside fields still need their own ownership policy.
from dataclasses import dataclass,replace
@dataclass(frozen=True)
class Config:
batch: int
base=Config(8)
[base.batch,replace(base,batch=16).batch]Result [8, 16]
中文
怎样从不可变实验配置派生只改一个参数的新版本?
dataclasses.replace 使用原对象的字段及指定变更调用初始化逻辑,得到同类型的新实例。
Python 算例与适用条件
基线批次为 8,派生配置改为 16,原配置继续可用于基准测试。内部可变字段仍需独立管理。
from dataclasses import dataclass,replace
@dataclass(frozen=True)
class Config:
batch: int
base=Config(8)
[base.batch,replace(base,batch=16).batch]结果 [8, 16]