The Data Classes Decorator
docs.python.org
docs.python.org
It has excellent support for JSON and JSON schemas out of the box.
Error messages are excellent! Tells you exactly what went wrong (most of the time) during validation.
I do use Pydantic even when Dataclass and NamedTuples are sufficient, I know that's a bit cargo cultish but it lowers the mental overhead by just having to perfect one of way of doing things.
That's exactly the point. The mental burden of remembering the quirks of (and having to choose between) namedtuples, typeddicts, dataclasses etc is very real.
https://pydantic-docs.helpmanual.io/usage/schema/#field-cust...
Coercion is quite powerful and saves me quite a bit of work. I write validation for config files that non programmers create. I would happily avoid explaining the difference between a 1 and a "1" to them whenever I can and let coercion do the work. It reduces the mental load on them too.
The Pydantic page itself provides some pretty nice notes on why it's awesome: https://pydantic-docs.helpmanual.io/#rationale
from typing import NamedTuple
class Coord(NamedTuple):
x: int
y: int
I would prefer immutable records over dataclasses on many occasions.On one one hand: yay types. On the other hand… yeah, this isn’t Python anymore. What used to be a fairly simple language with some well known quirks evolved into an ungrokable katamari of every single possible language feature, a duct taped mush of pieces from different puzzle sets.
I guess it’s a victim of its own success. I just wish it stayed good old, Python, and people would just use different languages for different needs instead of needing one general purpose language for everything.
@decorator some_func
is simply
some_func = decorator(some_func)
There is no C++style "Here is 100 more arcane rules and 1000 exceptions and meta-rules that govern their interaction and application". It's all consistent additions to the language that does nothing but abstract out what you could do by hand but more verbose-ly and error-prone-ly. In fact, nothing in the above comments except type annotations are "language features" at all, they are libraries, and not even implicitly imported at that.
That's not true. You can use make_dataclass the same way you can use namedtuple:
>>> from dataclasses import make_dataclass
>>> A = make_dataclass("A", ["x", "y", "z"])
>>> A(1, 2, 3)
A(x=1, y=2, z=3)
It is true that if you want to use @dataclass you have to use annotations, just the way you do with typing.NamedTuple. But as others have noted, the annotation is mostly ignored.[edited for formatting]
Namedtuple is intended for when you need a tuple. I’ve used it for e.g numpy array shapes, so image data has names (imgshape.width instead of imgshape[1]). There, you need an actual tuple (or subclass of tuple if you want).
[1]: https://github.com/python/cpython/blob/3.10/Lib/collections/...