from typing import NamedTuple
class Coord(NamedTuple):
x: int
y: int
I would prefer immutable records over dataclasses on many occasions. 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.
[1]: https://github.com/python/cpython/blob/3.10/Lib/collections/...
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).
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]