Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Named 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.



I 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.


I 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.


Isn’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 .


Named 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.


> 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: