classification
Title: typing.NamedTuple does not support mixins
Type: behavior Stage:
Components: Library (Lib) Versions: Python 3.7
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: levkivskyi, rectalogic, rhettinger
Priority: normal Keywords:

Created on 2019-04-03 13:07 by rectalogic, last changed 2019-04-06 21:34 by levkivskyi.

Messages (2)
msg339390 - (view) Author: Andrew Wason (rectalogic) Date: 2019-04-03 13:07
Subclassing typing.NamedTuple an inheriting from a mixin class does not work. It does work for collections.namedtuple, and can be worked around by modifying typing.NamedTupleMeta:

>>> import collections
>>> import typing
>>>
>>>
>>> class Mixin:
...     def mixin(self):
...         return "mixin"
...
>>>
>>> class CollectionsNamedTuple(Mixin, collections.namedtuple('CollectionsNamedTuple', [
...     "a",
...     "b",
... ])):
...     pass
...
>>>
>>> class TypingNamedTuple(Mixin, typing.NamedTuple):
...     a: str
...     b: str
...
>>>
>>> class NamedTupleMeta(typing.NamedTupleMeta):
...     def __new__(cls, typename, bases, ns):
...         cls_obj = super().__new__(cls, typename + '_nm_base', bases, ns)
...         bases = bases + (cls_obj,)
...         return type(typename, bases, {})
...
>>>
>>> class FixedTypingNamedTuple(Mixin, metaclass=NamedTupleMeta):
...     a: str
...     b: str
...
>>>
>>> cnt = CollectionsNamedTuple("av", "bv")
>>> tnt = TypingNamedTuple("av", "bv")
>>> ftnt = FixedTypingNamedTuple("av", "bv")
>>>
>>> cnt.mixin()
'mixin'
>>> ftnt.mixin()
'mixin'
>>> tnt.mixin()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'TypingNamedTuple' object has no attribute 'mixin'
msg339546 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2019-04-06 21:34
Hm, it looks like we can support this. I however don't think the proposed "patch" is the right way to fix it, since this makes the implementation with and without a mixin quite different.

Also I am not sure I will have time to work on this in the nearest month.
History
Date User Action Args
2019-04-06 21:34:20levkivskyisetmessages: + msg339546
2019-04-03 14:37:36gvanrossumsetnosy: - gvanrossum
2019-04-03 14:12:04matrixisesetnosy: + rhettinger
2019-04-03 13:15:33xtreaksetnosy: + gvanrossum, levkivskyi
2019-04-03 13:07:30rectalogiccreate