Python Typing:如何让 Type[C] 与 TypeVars 和泛型一起工作?



我正在尝试弄清楚如何让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]调用一个特定的函数时,我期望得到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]不起作用,则可能应该更新它们。

最新更新