[issue43923] Can't create generic NamedTuple as of py3.9

FHTMitchell report at bugs.python.org
Fri Apr 23 12:22:56 EDT 2021


New submission from FHTMitchell <fhtmitchell at gmail.com>:

As of python 3.9, you now can't have multiple inheritance with `typing.NamedTuple` subclasses. This seems sensible, until you realise that `typing.Generic` works via inheritance. This fails whether or not `from __future__ import annotations` is enabled.

example:

```
class Group(NamedTuple, Generic[T]):
     key: T
     group: List[T]
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-fc238c4826d7> in <module>
----> 1 class Group(NamedTuple, Generic[T]):
      2     key: T
      3     group: List[T]
      4 

~/.conda/envs/py39/lib/python3.9/typing.py in _namedtuple_mro_entries(bases)
   1818 def _namedtuple_mro_entries(bases):
   1819     if len(bases) > 1:
-> 1820         raise TypeError("Multiple inheritance with NamedTuple is not supported")
   1821     assert bases[0] is NamedTuple
   1822     return (_NamedTuple,)

TypeError: Multiple inheritance with NamedTuple is not supported
```

This worked fine in python 3.7 and 3.8 and as I understand it was one of the motivating cases for pep 560. 

The change was made as part of bpo-40185: Refactor typing.NamedTuple. Whilst the obvious alternative is "use dataclasses", they don't have the same runtime properties or implications as namedtuples.

----------
messages: 391705
nosy: FHTMitchell
priority: normal
severity: normal
status: open
title: Can't create generic NamedTuple as of py3.9
versions: Python 3.10, Python 3.11, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43923>
_______________________________________


More information about the Python-bugs-list mailing list