3 ms·
Not a python guy, so confused as to why a thing called namedtuple behaves like dataclasses, what are their different usecases?
by nsonha 5y ago
Not a python guy, so confused as to why a thing called namedtuple behaves like dataclasses, what are their different usecases?
- aix1 5y agoNamed tuples have been around for a long time (since 2.6), whereas dataclasses are a relatively recent addition to the standard library (3.7). Their differences are highlighted in the dataclasses PEP: https://www.python.org/dev/peps/pep-0557/#why-not-just-use-namedtuple https://www.python.org/dev/peps/pep-0557/#why-not-just-use-n...
- nsonha 5y agolooks like the key thing is immutability
- aix1 5y agoTo clarify, both named tuples and dataclasses can be immutable (the former are always immutable and the latter can be made immutable with `frozen=True`). There is no way, however, to make a named tuple mutable.
- dreamofkoholint 5y agoKey thing for me was the ability to add type hinting
- rguillebert 5y agoNamedtuples also behave like tuples, which is great when you want to incrementally turn tuples into classes but if you want an easy way of creating classes, it's probably not a good idea to have them behave like tuples. Plus dataclasses have more features.
- pletnes 5y agoThere’s also the fact that sometimes you need an actual tuple - in some places (C extensions like numpy, opencv, …) and a dataclass just doesn’t work.
- jeeeb 5y agoFrom a users perspective data classes look kind of like a C struct and in particular include type annotations so fit well with type checkers. They also allow for default values and give more control over generating equality, hash, string and initialisation methods. Comparatively named tuples are an older language feature which essentially allow you to define named accessors for tuple elements. IIRC, these days you can also define type annotations for them. Their use case essentially overlap. Personally I much prefer data classes.
- progval 5y agoFWIW, you can also add type annotations for namedtuples, with a syntax similar to data classes: https://docs.python.org/3/library/typing.html#typing.NamedTuple https://docs.python.org/3/library/typing.html#typing.NamedTu... You can even type dictionaries this way: https://docs.python.org/3/library/typing.html#typing.TypedDict https://docs.python.org/3/library/typing.html#typing.TypedDi...
- nsonha 5y agoThis is my confusion learning python, just pick a thing for struct will ya :)