【发布时间】:2019-02-26 04:04:55
【问题描述】:
我试图弄清楚如何让 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)
【问题讨论】:
标签: python generics type-hinting