Repository navigation
Fix crash on invalid _fields in named-tuple-like classes - #1259
Conversation
5e35c0b to
98334f6
Compare
98334f6 to
a4b4c08
Compare
| && PyType_IsSubtype((PyTypeObject *)t, &PyTuple_Type) | ||
| && PyObject_HasAttr(t, state->mod->str__fields) | ||
| ); | ||
| // There's no `NamedTuple` class, it is not really easy to check. |
There was a problem hiding this comment.
Really a shame that there's no common base / metaclass for this. Do you know if there's a reason for this, or is it just historical?
There was a problem hiding this comment.
This happens to be an implementation detail: when collection.namedtuple was first introduced it was not possible to be used as a baseclass, only as a function call: https://github.com/python/cpython/blob/50082b8d89392b7655eb9a2790731b613cbc620f/Lib/collections/__init__.py#L361-L533
Later it started supporing subclassing and custom methods.
Basically, it is a class maker function.
typing.NamedTuple just allows doing the semantically identical thing: https://github.com/python/cpython/blob/50082b8d89392b7655eb9a2790731b613cbc620f/Lib/typing.py#L3015-L3019
So, nobody ever expected NamedTuple or namedtuple to be a serialization model :(
There was a problem hiding this comment.
Mhm. Would be nice to have this. You think it's worth an attempt to contribute this upstream? Checking if something's a NamedTuple would be rather helpful. Even something like datclasses, e.g. a canonical static attribute on the namespace, and a collections.isnamedtuple function
There was a problem hiding this comment.
It is worth trying, but I doubt it will make it into the source code :)
Before this change we used
PyTuple_GET_SIZE(fields);without checkingfieldsto betuple.I changed how
NamedTupleis detected. Now, it must have all the required fields.