3 ms·
Author could have used NamedTuple instead of dataclass or TypedDict: from typing import NamedTuple class Point(NamedTuple): x: int y:
by heavyset_go 2y ago
Author could have used NamedTuple instead of dataclass or TypedDict:
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
z: int
I don't see "don't use namedtuples in APIs" as a useful rule of thumb, to be honest. Ordered and iterable return-types make sense for a lot of APIs. Use them where it makes sense.
- notpushkin 2y agoAuthor argues that named tuples are bad (it’s literally the article title) so I think you miss the point?
- PittleyDunkin 2y agoThe author also argues for readability over semantics, so I'm not sure they got the point to begin with.
- heavyset_go 2y agoThe author claims that the reason people reach for namedtuples is brevity, but I'd argue to the contrary and include the modern syntax for defining a namedtuple. The syntax is nearly identical to TypedDict and dataclass. There are other reasons to reach for namedtuples, for example when order or iterability matter. I don't see a general rule of not using namedtuples in APIs to be that useful. Use the right tool when the need calls for it.
- mont_tag 2y agoRight. It takes equal effort to define a named tuple, typed dict or dataclass. Mostly people just reach for the tool that does what they want, named tuples for tuply stuff, typed dicts for mapping applications, and dataclasses when you actually want a class.
- rtpg 2y agoI feel like "consider dataclasses as a useful default" is decent advice. You get the stuff you get from `NamedTuple`, but you can also easily add helper methods to the class as needed. And there are other dataclass goodies (though some things I find to be a bit anti-feature-y).
- heavyset_go 2y ago> I feel like "consider dataclasses as a useful default" is decent advice. I agree. > You get the stuff you get from `NamedTuple`, but you can also easily add helper methods to the class as needed. And there are other dataclass goodies (though some things I find to be a bit anti-feature-y). I've seen examples where dataclasses were used when order matters, however, hence why I'm not comfortable with a general rule against namedtuples. Sometimes order and iterability matter, and dogmatically reaching for a different data type that doesn't preserve that information might be the wrong choice.
- david2ndaccount 2y agoYou can have methods with NamedTuple
- rtpg 2y agoOh, with the class declaration version? I never considered that, but feels obvious now.
- d0mine 2y agoThe point of the article is that: do not return objects that are sequences too when a struct would suffice. Though the provided options are not immutable and it is much more important than whether you leak o[0] access. dataclass(frozen=True) is the only acceptable alternative.