我试图弄清楚如何使Python通用类型提示与Type [C]的构造函数参数配合使用。考虑以下代码示例:
class Foo(object):
fooval: str
def __init__(self, val):
self.fooval = val
class Bar(object):
barval: str
def __init__(self, val):
self.barval = val
T = TypeVar('T', Foo, Bar)
class FooBarContainer(Generic[T]):
child: T
# Type[T] seems logical here, but that's not valid according to the docs
def __init__(self, ctorable: Type[Union[Foo, Bar]], val):
self.child = ctorable(val)
baz = FooBarContainer(Foo, val)
# This does not get flagged by type-checkers, but will obviously fail at runtime
failure = baz.child.barval
尝试使用Type [T]会导致类型检查器错误:
预期的类型[T],得到的类型[Foo]
因此,这里的目标是弄清楚如何通过键入使TypeVars与Type [C]一起使用。通过这种方式,静态分析将知道,当我使用特定的Type [T]调用特定的func时,我希望可以将T返回。我似乎在这里找不到任何对我有帮助的文档。
处理功能时也会出现相同的问题。例如,这是有效的语法,但显然在键入方面无效:
def initor(thing_type: Type[Union[Foo, Bar]], val) -> T:
return thing_type(val)
最佳答案
您能说明“这里的Type [T]似乎合乎逻辑,但这在文档中是无效的”的意思吗?
特别是,您在看什么文档?以下代码使用mypy 0.630对我来说可以正常工作:
class FooBarContainer(Generic[T]):
child: T
def __init__(self, ctorable: Type[T], val) -> None:
self.child = ctorable(val)
val = 3
baz = FooBarContainer(Foo, val)
# Mypy reports a `"Foo" has no attribute "barval"` error
failure = baz.child.barval
如果文档暗示给
ctorable
类型Type[T]
不起作用,则可能应该对其进行更新。