3 ms·
Another problem brought about by their design being backwards-compatible with tuples is that you get wonky equality rules where two namedtuples of different typ
by dathery 2y ago
Another problem brought about by their design being backwards-compatible with tuples is that you get wonky equality rules where two namedtuples of different types and with differently-named attributes can compare as equal:
>>> Foo = namedtuple("Foo", ["bar"])
>>> Baz = namedtuple("Baz", ["qux"])
>>> Foo(bar="hello") == Baz(qux="hello")
True
This also happens with the "new-style" namedtuples (typing.NamedTuple).
I like the convenience of namedtuples but I agree with the author: there are enough footguns to prefer other approaches.
- mont_tag 2y agoThis seems like an invented problem that never comes up in practice. It is no more interesting than numpy arrays evaluating as equal even when they conceptually not comparable: >>> temperatures_fahrenheit = np.array([10, 20, 30]) >>> temperatures_celsius = np.array([10, 20, 30]) >>> temperatures_fahrenheit == temperatures_celsius array([ True, True, True])
- quotemstr 2y agoThe numpy equality thing is actually an enormous footgun, especially for people new to numeric Python. The equality for numpy and its derivates should have had the traditional Python meaning (yielding a bool), with the current operation (yielding a mask) should have been put under a named method.
- deleted 2y ago[deleted]
- beng-nl 2y agoNot that I find your argument invalid, but you’re not arguing against GP. At risk of belaboring the point or being redundant, GP is making the point that the Celsius vs Fahrenheit meaning of the arrays makes them Semantically different and therefore the equality could Be taken to be misleading when this is taken into account. GP thinks this is nonsense and draws a parallel with named tuples.
- dathery 2y agoI've usually seen it come up when people try to hash the objects to use as dictionary keys or in sets, and then encounter very hard-to-troubleshoot issues later on. Obviously it's a bit weird to hash a bunch of objects of different types, but it's just one example of the footguns that namedtuples have and why I prefer other approaches.