4 ms·
I think you are missing the best aspects of namedtuple. The positional properties are there to ease interaction with other APIs. The vast majority of access sho
by nerpderp83 9y ago
I think you are missing the best aspects of namedtuple. The positional properties are there to ease interaction with other APIs. The vast majority of access should be through `.member`
- abecedarius 9y agoNo, I agree with eesmith: I've been bitten multiple times by bugs from namedtuple objects providing the tuple interface which I'd never intended to use. So I stopped using namedtuple in favor of a new more-restricted module I wrote to replace it.
- nerdponx 9y agoOut of curiosity, what kind of bugs have you see that arose from "providing the tuple interface" inappropriately?
- abecedarius 9y agoAll I remember clearly still is the baffled frustration, like you feel when a C compiler optimizes out undefined behavior you didn't know about. I was using namedtuple in generally this kind of way: https://github.com/darius/tinyhiss/blob/master/terp.py#L90 https://github.com/darius/tinyhiss/blob/master/terp.py#L90 (this was a trampolined interpreter for a dialect of Smalltalk). One thing that could happen is, when you might expect to see a type error if you take one of these objects x and mistakenly write x[0], it'd just continue on with some field value. Or if you mistakenly try to iterate over x, you can. Or maybe you were generically walking a tree of objects and didn't intend for an instance of one of these classes to have children. The bafflement I ran into was weirder than these; maybe it had to do with the fact that inheritance was mixed in here too? And I think I'd defined `__getitem__` in some of these classes one of those times. Sorry I can't remember more. To write https://github.com/darius/tailbiter https://github.com/darius/tailbiter I had to know quite a bit about Python, but it's a big language! It was a mistake to assume I could use namedtuple as just a convenient way to define a struct type without grokking all its details.
- yen223 9y agoPython's JSON serializer treats NamedTuples as lists. Not wrong once you understand NamedTuples are tuples, but completely unintuitive. In [13]: from collections import namedtuple In [14]: import json In [15]: nt = namedtuple("Test", ["field1", "field2"]) In [16]: sample = nt(field1="foo", field2="bar") In [17]: json.dumps(sample) Out[17]: '["foo", "bar"]'
- nerpderp83 9y agoI could see that. If the majority of your use case just immutability and named member access, the tupitility of it doesn't matter much. In that regard, we just need a lightweight way to specify immutable structs, which I would throw a tupleware party to support. Maybe include a .to_tuple() method on your immutable structs