我正在尝试创建NamedTuple的通用版本,如下所示:
T1 = TypeVar("T1")
T2 = TypeVar("T2")
class Group(NamedTuple, Generic[T1, T2]):
key: T1
group: List[T2]
g = Group(1, [""]) # expecting type to be Group[int, str]
但是,我收到以下错误:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
我不确定如何实现我在这里尝试做的事情,或者如果这可能是某种程度上的打字机制中的错误.
解决方法:
所以这是一个元类冲突,因为在python 3.6中输入NamedTuple和Generic使用不同的元类(typing.NamedTupleMeta和typing.GenericMeta),python无法处理.我担心没有解决方案,除了从元组子类并手动初始化值:
T1 = TypeVar("T1")
T2 = TypeVar("T2")
class Group(tuple, Generic[T1, T2]):
key: T1
group: List[T2]
def __new__(cls, key: T1, group: List[T2]):
self = tuple.__new__(cls, (key, group))
self.key = key
self.group = group
return self
def __repr__(self) -> str:
return f'Group(key={self.key}, group={self.group})'
Group(1, [""]) # --> Group(key=1, group=[""])
由于PEP 560这是在python 3.7中修复的:
Python 3.7.0b2 (v3.7.0b2:b0ef5c979b, Feb 28 2018, 02:24:20) [MSC v.1912 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import *
>>> T1 = TypeVar("T1")
>>> T2 = TypeVar("T2")
>>> class Group(NamedTuple, Generic[T1, T2]):
... key: T1
... group: List[T2]
...
>>> g = Group(1, [""])
>>> g
Group(key=1, group=[''])
虽然我没有检查过,但是类型检查器在python 3.7中如何处理我的解决方案/你的解决方案.我怀疑它可能不是无缝的.
编辑
我找到了另一个解决方案 – 制作一个新的元类
import typing
from typing import *
class NamedTupleGenericMeta(typing.NamedTupleMeta, typing.GenericMeta):
pass
class Group(NamedTuple, Generic[T1,T2], metaclass=NamedTupleGenericMeta):
key: T1
group: List[T2]
Group(1, ['']) # --> Group(key=1, group=[''])