mirror of
https://github.com/vinta/awesome-python.git
synced 2026-11-10 01:34:28 -06:00
docs: add dataclasses to Built-in Classes Enhancement category intro
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -4,9 +4,12 @@ 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](https://docs.python.org/3/library/dataclasses.html) 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](https://docs.python.org/3/library/dataclasses.html#frozen-instances).
|
||||
|
||||
attrs [writes the dunder methods](https://www.attrs.org/en/latest/) that implement object protocols, so you don't have to. For new code, its docs [recommend the modern API](https://www.attrs.org/en/latest/names.html#tl-dr): `@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](https://www.attrs.org/en/latest/why.html#data-classes), like validators and converters, so a class that needs them goes to attrs. It [isn't a full serialization library](https://www.attrs.org/en/latest/overview.html#what-attrs-is-not), though: to serialize and validate your attrs classes, its docs point you to its sibling project, cattrs.
|
||||
|
||||
python-box installs Box, a [`dict` subclass](https://github.com/cdgriffith/Box) 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](https://github.com/cdgriffith/Box/wiki/Converters) 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](https://www.attrs.org/en/latest/why.html#dicts), and belongs in a class.
|
||||
|
||||
Reference in New Issue
Block a user