【发布时间】:2020-11-13 04:42:47
【问题描述】:
我正在尝试在 Python 的元类中键入 __new__ 方法,以便让 mypy 满意。代码将是这样的(取自pep-3115 - “Python 3000 中的元类”并精简了一点):
from __future__ import annotations
from typing import Type
# The metaclass
class MetaClass(type):
# The metaclass invocation
def __new__(cls: Type[type], name: str, bases: tuple, classdict: dict) -> type:
result = type.__new__(cls, name, bases, classdict)
print('in __new__')
return result
class MyClass(metaclass=MetaClass):
pass
这样,mypy 抱怨,Incompatible return type for "__new__" (returns "type", but must return a subtype of "MetaClass"),指向def __new__ 行。
我也尝试过:
def __new__(cls: Type[MetaClass], name: str, bases: tuple, classdict: dict) -> MetaClass:
然后 mypy 抱怨(关于return result 行):Incompatible return value type (got "type", expected "MetaClass")。
我也尝试过使用类型 var (TSubMetaclass = TypeVar('TSubMetaclass', bound='MetaClass')),结果与使用 MetaClass 相同。
使用super().__new__ 代替type.__new__ 得到了类似的结果。
正确的做法是什么?
【问题讨论】: