3 ms·
> Dataclasses instead of tuples or dictionaries The point is good in general, but it's still perfectly possible to use tuples and get all the field name and ty
by quietbritishjim 3y ago
> Dataclasses instead of tuples or dictionaries
The point is good in general, but it's still perfectly possible to use tuples and get all the field name and typing benefits: just use typed named tuples [1].
Unfortunately this is buried in the typing module. I couldn't even find it in the table if contents, and I knew what I was specifically looking for.
https://docs.python.org/3/library/typing.html#typing.NamedTuple https://docs.python.org/3/library/typing.html#typing.NamedTu...
- raverbashing 3y ago> typed banned tuples I think you mean typed named tuples
- quietbritishjim 3y agoOops, thanks! Fixed now
- deleted 3y ago[deleted]
- Kwpolska 3y agoNamed tuples, typed or not, are a bad idea for most data structures. They might make some sense when dealing with coordinates (x, y, z), but why would you want to use it for an Employee class, as shown in the example? This is a tuple, so you can iterate over it, employee[0] == "Guido", and employee[1] == 3. This isn’t useful in any way, it’s confusing, and it’s making it harder to change the order of fields in this class. Just use an actual class, not a class pretending to be a tuple sometimes.
- quietbritishjim 3y agoI wasn't saying that you always ought to use a named tuple instead of a dataclass. Only that, if you do want a tuple, that option is still available. Personally, I would use a tuple if I want something immutable. I realise you can do that with dataclasses by setting frozen=True but it feels a little over engineered to me.
- csunbird 3y agoIsn’t the whole point of named tuples to not iterate over indexes, but to iterate over field names instead, e.g employee.name, employee.salary? You can also use typing.namedtuple as a baseclass for your classes to have the same functionality .
- Kwpolska 3y agoNamed tuples have both field names and numeric indexes. If you iterate over a namedtuple, you just get the values. The field names are hidden in a _fields attribute, there is no way to iterate over (name, value) pairs.
- quietbritishjim 3y ago> there is no way to iterate over (name, value) pairs zip(x._fields, x) I get your point that it's not just a built in method though.
- psd1 3y agoI dipped my toe into NamedTuple. Where it falls down is that it requires a custom serialiser. Python's json library is a crock of shit once you've used .net. TypedDict turned out to be the winner. The runtime type is dict but you get all the benefits of type annotations. I dropped it into a crappy codebase without touching the calling methods.
- kobzol 3y agoI didn't know about that, thanks. I kind of agree with a sibling comment that in most cases you don't want to expose an indexer if the fields are named, but it might be useful sometimes.