【问题标题】:howto make subclassing with value parameters compatible with mypy generics?如何使用与 mypy 泛型兼容的值参数进行子类化?
【发布时间】:2019-10-27 18:20:38
【问题描述】:

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

我正在使用 Python 3.6.8(Ubuntu 18.04 的 Python3)和 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) # "???"

以下示例使用构建类的函数,在运行时可以正常运行,但不进行类型检查:mypy 无法将函数的结果识别为可派生的基类:

# 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"

【问题讨论】:

  • 你确定你叫它arg 而不是args 什么的吗? (如果我正确读取代码,两者都会失败,但arg 的错误消息似乎是错误的。)
  • (检查您使用此参数名称的所有位置,包括但不限于__init_subclass__ 的定义以及您尝试创建Bar 的位置。)
  • 没有其他地方使用该参数。 sn-ps 是独立的最小示例。我刚刚编辑了帖子以使其清楚。
  • 啊,在我预期的错误之前发生了另一个错误。

标签: python python-3.x mypy


【解决方案1】:

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

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

【讨论】:

  • 不是我希望的深度技术解决方案,而是常识解决方案。我希望我可以使用标准的 Ubuntu 18.04 Python,但与旧版本的缺陷作斗争是不值得的。谢谢您的帮助。我将您的答案标记为已接受。
猜你喜欢
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 2021-05-09
  • 1970-01-01
相关资源
最近更新 更多