如何使具有值参数的子类化与 mypy 泛型兼容?

howto make subclassing with value parameters compatible with mypy generics?

我正在寻找一种将参数传递给子程序的简单方法class。 https://www.python.org/dev/peps/pep-0487/ 提供了这样一种表示法:class C(Base, arg=value)。对于正常的 class,这可以完美地工作并通过 mypy 正确地进行类型检查,但是它失败了,因为泛型 class 继承了一些 Generic[T](请参见下面的代码)。我错过了什么?

我正在使用 Python 3.6.8(库存 Python3 of Ubuntu 18.04)和 mypy 0.740。

这里有两个最小的独立示例:可以将它们放在两个 .py 文件中,对它们进行类型检查并 运行 它们。

这段代码可以进行类型检查,运行没问题:

# ok.py
# PEP 487, adapted from QuestBase example

class Foo(object):
    variable = "???"
    def __init_subclass__(cls, arg: str, **kwargs) -> None:
        cls.variable = arg
        super().__init_subclass__(**kwargs) # type: ignore

class Bar(Foo, arg="value"): ...

print(Bar.variable)

此代码进行了类型检查,但在 运行 时间失败 TypeError: __init_subclass__() missing 1 required positional argument: 'arg':

# problem.py
from typing import Generic, TypeVar
T = TypeVar('T')

# PEP 487, adapted from QuestBase example

class Foo(Generic[T]):
    variable = "???"
    def __init_subclass__(cls, arg: str, **kwargs) -> None:
        cls.variable = arg
        super().__init_subclass__(**kwargs) # type: ignore

class Bar(Foo[T], arg="value"): ... # crash

崩溃日志:

Traceback (most recent call last):
  File "problem.py", line 12, in <module>
    class Bar(Foo[T], arg="value"): ... # crash
  File "/usr/lib/python3.6/typing.py", line 682, in inner
    return func(*args, **kwds)
  File "/usr/lib/python3.6/typing.py", line 1143, in __getitem__
    orig_bases=self.__orig_bases__)
  File "/usr/lib/python3.6/typing.py", line 978, in __new__
    self = super().__new__(cls, name, bases, namespace, _root=True)
  File "/usr/lib/python3.6/typing.py", line 137, in __new__
    return super().__new__(cls, name, bases, namespace)
  File "/usr/lib/python3.6/abc.py", line 133, in __new__
    cls = super().__new__(mcls, name, bases, namespace, **kwargs)
TypeError: __init_subclass__() missing 1 required positional argument: 'arg'

显然 Python 内部文件的崩溃揭示了我的文件中的问题。再一次,我错过了什么?

是否有真正经过类型检查的解决方案或解决方法?

下面的例子不是一个很好的解决方案(错误但类型检查):

# fake.py
from typing import Generic, TypeVar
T = TypeVar('T')


class Foo(Generic[T]):
    variable = "???"

class Bar(Foo[T]):
    variable = "value"

class KO(Foo[T]):
    ... # forgot assignment but still typechecks


print(KO.variable) # "???"

以下示例使用构建 class 的函数,在 运行 时没问题,但不进行类型检查:mypy 无法将函数的结果识别为可导出的基础class:

# param.py
from typing import Generic, TypeVar, Type
T = TypeVar('T')

class Foo(Generic[T]):
    variable = "???"

def bar(arg: str) -> Type[Foo[T]]:
    class C(Foo[T]):
        variable = arg
    return C

Bar: Type[Foo[float]] = bar("value")
print(Bar.variable)

class Baz(Bar): ... # doesn't typecheck
print(Baz.variable)

错误日志:

param.py:16: error: Variable "param.Bar" is not valid as a type
param.py:16: error: Invalid base class "Bar"

根据您的 Python 版本,Foo[T] 可能是 Foo 的子 class,也可能是其他一些奇怪的对象。 Python 3.6.8 是 Foo[T]Foo 的子 class 的版本之一。由于它是 Foo 的子 class,因此需要使用 arg 的某个值创建它,但它没有,因此出现错误。

在 Python 3.7 和 3.8 上,Foo[T] 不是 Foo 的子 class,事实上,它不是 class根本。在这些版本上,您的代码应该可以正常工作。 (我测试了 3.7.0,它工作了。)不过,我不指望它会保持良好状态。他们不断对 typing 内部进行奇怪的新更改,因此将来可能会出现问题。