awesome-python/website/data/category_intros/built-in-classes-enhancement.md
Vinta Chen 259bf48e3f docs: add dataclasses to Built-in Classes Enhancement category intro
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-08 20:41:37 +08:00

3.3 KiB

Skip hand-written dunder methods, and when you compare Python dataclass alternatives, pick attrs for its validators and converters. Box gives dicts dot access.

How to choose:

  • Classes with generated dunder methods, validators, and converters: attrs
  • Dicts read with dot notation, nested ones included: python-box
  • Generated dunder methods with nothing to install: dataclasses
  • Looking up a key by its value, with both directions in sync: bidict
  • A faster drop-in for the uuid module: uuid-utils

The standard library's dataclasses adds generated special methods such as __init__() and __repr__() to your classes. Put @dataclass on a class, and every class variable with a type annotation becomes a field. Pass frozen=True for read-only instances.

attrs writes the dunder methods that implement object protocols, so you don't have to. For new code, its docs recommend the modern API: @define on the class and field() for an attribute, or @frozen for immutable instances, with slots on by default. Type annotations stay optional. The standard library's dataclasses gave up features for simplicity, like validators and converters, so a class that needs them goes to attrs. It isn't a full serialization library, though: to serialize and validate your attrs classes, its docs point you to its sibling project, cattrs.

python-box installs Box, a dict subclass whose keys you can also read as attributes, even ones like "imdb stars". Nested dicts and lists become Box and BoxList objects, so dot access works all the way down: movie_box.Robin_Hood_Men_in_Tights.imdb_stars. It reads and writes JSON, YAML, TOML, and msgpack with methods like from_json() and to_json(), and to_dict() gives you plain dicts back. Keep Box for data whose keys change: attrs' docs say a dict with a fixed and known set of keys is an object, not a hash, and belongs in a class.

bidict gives you bidirectional mappings that work like dicts: look up a value by its key as usual, or a key by its value through .inverse, which stays in sync as you update the mapping. A single dict holding both directions mixes keys with values. Modeling the mapping correctly takes two one-way mappings kept in sync, which is what bidict does under the hood.

uuid-utils is a fast, drop-in replacement for Python's uuid module, powered by Rust. Import it under the module's name, import uuid_utils as uuid, and call uuid.uuid4() or uuid.uuid7() as usual. Django and some other frameworks require the standard library's own uuid.UUID instances. For those, import uuid_utils.compat instead, which returns them and still outperforms the standard library.