top | item 44675694

(no title)

ozkatz | 7 months ago

I agree grouping behaviors (functions) doesn't require classes, but since Python does not have structs, classes are the only way to provide types (or at least type hints) for non-scalar data. Dicts can only have a key type and value types, while lists/tuples can only carry one type.

    class Person:
        age: int
        name: str

Would have to be boiled down to `dict[str, Any]` (or worse, `tuple[Any]`). You could use `typing.NamedTuple` without defining a class (`NamedTuple('Person', [('name', str), ('age', int)])`) - but subjectively, this is much less readable than simply using a data class.

discuss

order

Arch-TK|7 months ago

The typing argument no longer holds. There are typed dicts where you specify field names and the respective key types. But in most cases you're still best off with just a dataclass. Bare classes shouldn't be the first thing you reach for when you want structure.

ozkatz|7 months ago

I agree dataclasses are a better alternative when you want a class that represents data :)

> There are typed dicts where you specify field names and the respective key types

The only way to achieve this that I'm aware of is PEP 589: subclassing TypedDict. Which I believe negates the argument in the post.