Batu Lab NotesPractical developer guides

Use dataclass field metadata for labels only

By Batu · English technical notes

Also published in our Blogger archive.

Dataclass field metadata is a useful home for small descriptive annotations such as user-interface labels. Here, each Product field supplies a label, and fields(Product) exposes Field objects from which the example builds a name-to-label mapping. The assertions verify the two chosen labels and separately confirm that the stored integer remains an integer value on the instance.

Keeping this metadata limited to presentation labels makes its role clear. A form renderer, table header helper, or documentation generator can consume the labels without changing construction, equality, or the value of price_cents. The dataclasses module itself does not interpret metadata; it provides it as an extension mechanism and exposes it through a read-only mapping proxy.

Consequently, metadata alone does not validate input, transform values, enforce ranges, or localize text. Code that needs those behaviors must implement and test them separately. Namespace keys are also sensible when several consumers share a model, for example {"ui.label": "Price (cents)"}. The dataclasses module is available from Python 3.7. Consult the official metadata documentation and fields() 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 dataclass, field, fields


@dataclass
class Product:
    sku: str = field(metadata={"label": "Stock keeping unit"})
    price_cents: int = field(metadata={"label": "Price (cents)"})


product = Product("A-17", 250)
labels = {item.name: item.metadata["label"] for item in fields(Product)}

assert labels == {
    "sku": "Stock keeping unit",
    "price_cents": "Price (cents)",
}
assert product.price_cents == 250
assert Product.__dataclass_fields__["sku"].metadata["label"] == "Stock keeping unit"

print(labels["sku"])
print(labels["price_cents"])
Stock keeping unit
Price (cents)