Python: Choose deep or shallow dataclass dictionaries
dataclasses.asdict() recursively converts a record and copies its contents. If you only need a dictionary of references to the current fields, build it with fields() and getattr() instead.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as record_snapshot_demo.py in an empty working directory:
from dataclasses import asdict, dataclass, fields
@dataclass
class Job:
labels: list[str]
job = Job(["queued"])
deep = asdict(job)
shallow = {field.name: getattr(job, field.name) for field in fields(job)}
job.labels.append("reviewed")
print("Original:", job.labels)
print("asdict:", deep["labels"])
print("Shallow:", shallow["labels"])
print("Shallow shares list:", shallow["labels"] is job.labels)Run it without -O so any assertions remain enabled:
python3 record_snapshot_demo.pyCaptured output:
Original: ['queued', 'reviewed']
asdict: ['queued']
Shallow: ['queued', 'reviewed']
Shallow shares list: TrueThe asdict() result keeps its separate list. The shallow mapping sees the appended label because it refers to the original list. Reassigning a field later would not update that dictionary entry: this is a snapshot of references, not a live view.
Limits and cleanup
asdict() recursively handles dataclasses, dictionaries, lists and tuples; other objects go through copy.deepcopy(). That can be expensive or fail for objects that cannot be copied. A shallow mapping avoids copying but does not isolate mutable values. Neither approach is automatic JSON serialization.
After testing, remove the example script from its working directory:
rm -- record_snapshot_demo.pyReference
Acknowledgements
This post was created with assistance from AI.