Skip to content
Python: Choose deep or shallow dataclass dictionaries

Python: Choose deep or shallow dataclass dictionaries

November 25, 2026

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.py

Captured output:

Original: ['queued', 'reviewed']
asdict: ['queued']
Shallow: ['queued', 'reviewed']
Shallow shares list: True

The 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.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on