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

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



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.


> typed banned tuples

I think you mean typed named tuples


Oops, thanks! Fixed now


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




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

Search: