Trending

World technology news

→
Python 3.7 dataclasses: separating a shipment model from input parsing
Software Engineering · 2018
Software Engineering2018

Python 3.7 dataclasses: separating a shipment model from input parsing

Build a validated shipment model with Python 3.7 dataclasses and exercise equality, immutability, and serialization boundaries.

Archive retrospective · Topic year 2018

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. What a three-field model needs
  2. Keep generated methods and business requirements separate
  3. A frozen dataclass can still hold mutable values
  4. Name the input and output boundaries
  5. Write down what equality means
  6. Earn the behavior with a small acceptance table

What a three-field model needs

A shipping team converts records from several depots into a common Python representation. Each shipment has an identifier, a positive weight in grams, and optional tags. A dictionary is easy to construct, but an external provider can silently start emitting weight as text or share a mutable list between records. Python 3.7, released in June 2018, added the dataclasses module described by PEP 557. This retrospective uses a synthetic shipment to explore which behaviors the decorator generates and which business decisions application code must make. It also distinguishes a shipment's identity from whether two observations of that shipment agree. Validation should reject bad input early enough that a later processing stage can trust the model.

Keep generated methods and business requirements separate

A dataclass can generate initialization, representation, and equality from fields. Annotating weight_g as int does not generally validate a supplied runtime value. The example states a positive integer requirement in __post_init__. It checks for an actual int so True is not interpreted as a weight. It refuses blank shipment numbers and blank tags, while leaving the decision about preserving spaces to the model's identifier policy. Tags must be a tuple of strings. An empty tuple is valid for a parcel with no assigned tags. Give each rule a passing and failing example. An ingestion layer that defaults a missing reading to zero may conceal the very data-quality failure this model is supposed to expose.

Machine learning pipelineConceptual sketch · summary of the article's technical flow
from dataclasses import dataclass
from typing import Tuple

@dataclass(frozen=True)
class Shipment:
    number: str
    weight_g: int
    tags: Tuple[str, ...] = ()

    def __post_init__(self):
        if not isinstance(self.number, str) or not self.number.strip():
            raise ValueError("number must be a non-empty string")
        if type(self.weight_g) is not int or self.weight_g <= 0:
            raise ValueError("weight_g must be a positive integer")
        if not isinstance(self.tags, tuple) or any(
            not isinstance(tag, str) or not tag.strip() for tag in self.tags
        ):
            raise ValueError("tags must be a tuple of non-empty strings")

A frozen dataclass can still hold mutable values

The frozen option prevents ordinary assignment to model fields. A list referenced by a field could still be changed from inside or outside the object. Our example stores a tuple whose entries are strings. Its empty default is safe to share. An intake form may need mutable staging with field(default_factory=list) for a fresh list per object. Convert that list to a tuple when building the committed model. Make two empty forms, add a tag to one, and check the other is unchanged. A dataclasses.replace call can make a revised object and retain the original for a history comparison. A frozen object does not manage concurrent updates to its database record. That is a separate persistence rule.

Name the input and output boundaries

The loader expects a JSON array of tags, then converts it to a tuple. Converting an unchecked string such as cold would produce a tuple of characters. Missing required fields can be converted into structured input errors at the service boundary. An explicit serializer names every public field and writes a schema version. Adding an internal note to the dataclass later will not automatically disclose it to that client. The asdict helper is useful in contexts where the whole object is meant to be transformed. It does not choose your public schema. Validate external schema versions before calling the example adapter when your depot protocol has versions. Compare equivalent records from each producer against the same domain value.

def load_shipment(record):
    tags = record.get("tags", [])
    if not isinstance(tags, list):
        raise ValueError("tags must be an array")
    return Shipment(record["number"], record["weight_g"], tuple(tags))

def export_shipment(model):
    return {
        "schema": 1,
        "number": model.number,
        "weight_g": model.weight_g,
        "tags": list(model.tags),
    }

assert load_shipment({"number": "S-42", "weight_g": 1250}) == Shipment("S-42", 1250)
assert export_shipment(Shipment("S-42", 1250, ("cold",)))["tags"] == ["cold"]

Write down what equality means

Generated equality compares designated fields of the same class. Two values may share their shipment number and differ in weight; they should not compare equal as observations in this example. A deduplication rule by shipment number should key a map or database constraint on that identifier explicitly. A set of whole model objects will not automatically enforce your shipment identity rule. Tags introduce a different choice. Tuple order matters to equality. If tag order has no domain meaning, choose a normal form or a different field type deliberately. Test how repetition and order interact with updates, especially when two depots export the same tags differently. Revisit equality tests if later additions should not change the observation's identity.

Earn the behavior with a small acceptance table

Test a valid shipment, missing fields, numeric strings, True as weight, zero and negative weight, a scalar tag, and an empty tag string. Verify exported field names and values without relying on object key order. Return enough detail to identify the input field while keeping the entire payload out of broad logs. The snippets use Python 3.7 syntax, without later dataclass parameters for keyword-only fields or slots. A maintained deployment still needs to exercise these contracts on its supported runtime. Dataclasses reduce handwritten method code. Their lasting contribution in this example is making the boundary between external representation, domain validation, and equality compact enough to read and test. A rejected record can then be traced without inventing a replacement value.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.