[issue36517] typing.NamedTuple does not support mixins
Andrew Wason
report at bugs.python.org
Wed Apr 3 09:07:30 EDT 2019
New submission from Andrew Wason <rectalogic at rectalogic.com>:
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'
----------
components: Library (Lib)
messages: 339390
nosy: rectalogic
priority: normal
severity: normal
status: open
title: typing.NamedTuple does not support mixins
type: behavior
versions: Python 3.7
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36517>
_______________________________________
More information about the Python-bugs-list
mailing list