【发布时间】: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