dataclasses.replace Derives Updated Copies

Produce updated frozen dataclass instances with dataclasses.replace: overridden keywords, untouched remainder, and a chain of traceable copies.

PythonData Integrity

Code

pythonsnippet
24 lines
from dataclasses import dataclass, replace


@dataclass(frozen=True)
class Flight:
    code: str
    status: str = 'scheduled'
    gate: str = 'TBD'


original = Flight('AA118', gate='B12')
print('original:', original)

# frozen 实例不能改字段:dataclasses.replace 生成覆盖指定字段的更新副本
boarded = replace(original, status='boarding')
print('updated :', boarded)

# 其余字段原样带过去,原实例不受影响
print('untouched:', original.status == 'scheduled', original.gate == 'B12')

# 派生链:每一步都是新对象,历史状态可追踪
enroute = replace(boarded, status='enroute', gate='B14')
chain = [f'{f.code}:{f.status}@{f.gate}' for f in (original, boarded, enroute)]
print('chain:', ' | '.join(chain))

Output

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

original: Flight(code='AA118', status='scheduled', gate='B12')
updated : Flight(code='AA118', status='boarding', gate='B12')
untouched: True True
chain: AA118:scheduled@B12 | AA118:boarding@B12 | AA118:enroute@B14

What the code does

dataclasses.replace Derives Updated Copies is built around the class Flight.

Top-level bindings original, boarded, enroute, chain hold the demo state — nothing sits inside a function scope.

Applying it

Output lines are prefixed (original:, updated :, untouched:), making each step’s effect easy to spot.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `original`, `boarded`, `enroute`.