python - 如何使用与 mypy 泛型兼容的值参数进行子类化?
问题描述
我正在寻找一种将参数传递给子类的简单方法。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"
解决方案
根据您的 Python 版本,Foo[T]
可能是 的子类Foo
,也可能是其他一些奇怪的对象。Python 3.6.8Foo[T]
是Foo
. 由于它是 的子类Foo
,因此需要使用 的某个值创建arg
它,但它没有,因此出现错误。
在 Python 3.7 和 3.8 上,Foo[T]
它不是 的子类Foo
,事实上,它根本不是一个类。在这些版本上,您的代码应该可以正常工作。(我测试了 3.7.0,它工作正常。)不过,我不会指望它保持正常。他们不断对typing
内部进行奇怪的新更改,因此将来可能会出现问题。
推荐阅读
- python - 从熊猫的数据框中删除字符串
- python - 如何使用 URL 参数预填充表单 (Django)
- angular - 从反应形式Angular的输入字段中获取更新的值
- python - tensorflow mnist 神经网络模型精度低
- python - 在数据框中获取每列仅更改 1 个或更多值的相似行
- r - 使用 ggplot 重新排列我的 y 轴变量时遇到问题
- javascript - 产量*和产量之间的差异
- python-3.x - 在 NetworkX 中分配节点属性时出现 TypeError
- python - AttributeError:“分类”对象没有属性“猫”
- android - 示例 java 应用程序共享锚不返回锚号