asdict And replace Clone Dataclass Records

Clone dataclass records with asdict, astuple, and replace: copies run deep through nested dataclasses, and replace rewrites fields without touching originals.

PythonData Integrity

Code

pythonsnippet
26 lines
from dataclasses import dataclass, asdict, astuple, replace, field

@dataclass
class Item:
    sku: str
    qty: int = 0
    tags: list = field(default_factory=list)

item = Item("SKU-1", 3, ["new"])
print("asdict:", asdict(item))
print("astuple:", astuple(item))

# replace 生成改字段的副本:原记录保持不变(不可变更新风格)
revised = replace(item, qty=10)
print("revised:", revised)
print("original intact:", item.qty == 3)

# asdict 深入嵌套结构逐层转换;改副本不影响原对象
@dataclass
class Order:
    items: list

order = Order([item])
dumped = asdict(order)
dumped["items"][0]["qty"] = 999
print("nested untouched:", order.items[0].qty == 3)

Output

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

asdict: {'sku': 'SKU-1', 'qty': 3, 'tags': ['new']}
astuple: ('SKU-1', 3, ['new'])
revised: Item(sku='SKU-1', qty=10, tags=['new'])
original intact: True
nested untouched: True

How it works

The moving parts are the class class.

The file’s state is a handful of top-level bindings: item, revised, order, dumped.

Caveats

  • No dependency declarations exist; dataclasses and the rest come with the interpreter.

Applying it

Running the file prints labeled results such as asdict:, astuple:, revised: — every step leaves its own tagged line.

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `dataclasses`. Its state lives in module-level bindings: `item`, `revised`, `order`.