3 ms·
Many python-ists have strong opinions on this, and they're fun to type, so I'll repeat mine. A type-homogeneous, variable length sequence (List[int]) should be
by joshuamorton 8y ago
Many python-ists have strong opinions on this, and they're fun to type, so I'll repeat mine.
A type-homogeneous, variable length sequence (List[int]) should be a list/generator/etc. or in some cases a tuple (for example if it was declared explicitly). Other great places for a tuple: the default argument for something that takes in a Sequence, since defaulting to an empty list can be dangerous.
However, for immutable, fixed-length, type-heterogenous sequences (which is where tuples are often used, implicitly as return types etc), a namedtuple (python's lightweight record type) is almost always superior (the only question is "is it worth it to define this"), and for mutable, fixed-length, type-heterogenous sequences (ie. points you can modify), dataclasses/attrs (python3.7 standard library dataclasses, attrs in python2.7+) are almost certainly preferable.
Basically, when you have a known number of attributes, you can give them names better than `[0]` and `[1]`.
- mhneu 8y agoYes Python code is often crying out for names better than [0] and [1]. And the big problem with namedtuples is that definition is so heavyweight - requires a new line of code, a new class object, picking the scope for that class (top-level means you have to keep track of your nonlocal definition), and namedtuples often block pickling. I use argparse.Namespace but it has some memory issues namedtuple was invented to solve. You can use a pandas series which has advantages, esp with many similar objs, but brings a new dependency and has some of the definitional problems. Python is crying out for a lightweight namedtuple for this purpose.
- heavenlyblue 8y agoJust use typing.NamedTuple.
- mhneu 8y agoThat has the same problems with the extra class definition: extra lines of code, choice of scope to define the new class, and maybe issues with pickling.