Convert a dataclass to a dict without assuming deep validation

dataclasses.asdict() converts a dataclass instance into a dictionary of its fields. It recurses into nested dataclasses, dictionaries, lists, and tuples; other objects are copied with copy.deepcopy(). In this example, the nested Address becomes a nested dictionary and tags becomes a list in the exported record.

The identity and mutation checks demonstrate an important consequence for this fixture: changing the exported list does not change customer.tags, and the nested exported address is not the original dataclass object. They do not establish that arbitrary custom values can always be deep-copied, nor that the resulting dictionary is valid for a database, JSON encoder, or external API.

Conversion is not validation. asdict() does not inspect whether postal_code has a required format, whether tags are allowed, or whether every value complies with a schema. Validate at the relevant boundary—during construction, before persistence, or before encoding—using rules that your application owns. If a shallow mapping is needed, the documentation provides a fields()-based pattern instead. asdict() is available with dataclasses in Python 3.7. See the official asdict() reference.

AI assistance disclosure: this article was drafted with AI assistance and should be adapted to the application’s own data rules.

from dataclasses import asdict, dataclass


@dataclass
class Address:
    city: str
    postal_code: str


@dataclass
class Customer:
    name: str
    address: Address
    tags: list[str]


customer = Customer("Ada", Address("Lima", "15001"), ["new"])
record = asdict(customer)

assert record == {
    "name": "Ada",
    "address": {"city": "Lima", "postal_code": "15001"},
    "tags": ["new"],
}
assert record["address"] is not customer.address
record["tags"].append("exported")
assert customer.tags == ["new"]

print(record)
{'name': 'Ada', 'address': {'city': 'Lima', 'postal_code': '15001'}, 'tags': ['new', 'exported']}

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic