4 ms·
What scenarios would it be useful for?
by collyw 8y ago
What scenarios would it be useful for?
- coldtea 8y agoWherever you want to store precisely N attributes, but also want to be able to mutate them. E.g. points on a plane (x,y) and an algorithm that sums them to find some center etc.
- js2 8y agoUse a class with __slots__ for that.
- deleted 8y ago[deleted]
- orf 8y agoThis is the correct answer for this if you're using Python and have lots of small objects with fixed attributes. In [1]: class A: ...: __slots__ = ('a', 'b') ...: def __init__(self): ...: self.a = 1 ...: self.b = 2 ...: In [3]: get_size(A()) Out[3]: 112 In [4]: get_size((1,1)) Out[4]: 120 Smaller than a tuple. Not to say that 112 bytes is great, but __slots__ can really help with memory usage. Without: In [23]: get_size(A()) Out[23]: 324 A named tuple, while not mutable, is 92 bytes with those two attributes.
- joshuamorton 8y agoMany 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.
- dagw 8y agoSounds like a case where the new Data classes could be used. But for performance reasons you'd probably want to use a numpy array to store your points if you're going to be doing a lot of operations over them.