Python 从与TypeVar关联的具体类型获取内部类型
我正在使用python中的Python 从与TypeVar关联的具体类型获取内部类型,python,mypy,Python,Mypy,我正在使用python中的mypy和键入模块。假设我有一个泛型类型: ContainerT = TypeVar('ContainerT') class Thingy(Generic[ContainerT]): pass 但是,我想在与TypeVar相关联的具体类型中找到另一个类型,如下面的示例所示: class SomeContainer(object): Iterator = SomeCustomIterator ContainerT = TypeVar('Contain
mypy
和键入模块。假设我有一个泛型类型:
ContainerT = TypeVar('ContainerT')
class Thingy(Generic[ContainerT]):
pass
但是,我想在与TypeVar相关联的具体类型中找到另一个类型,如下面的示例所示:
class SomeContainer(object):
Iterator = SomeCustomIterator
ContainerT = TypeVar('ContainerT')
class Thingy(Generic[ContainerT]):
def foo(self) -> ContainerT.Iterator:
pass
我得到一个错误,说TypeVar
没有成员Iterator
。有没有另一种方法来重新表述这一点,以便我可以将一种类型与另一种类型关联起来
谢谢。也许你正在考虑这样的事情
from\uuuuu future\uuuuu导入注释
从abc导入法
从输入import Generic、TypeVar、迭代器、Protocol
_迭代器=类型变量(“迭代器”,绑定=迭代器,协变=真)
类容器:
迭代器:迭代器[int]
def uuu init uuu(self,迭代器:迭代器[int]):
self.iterator=迭代器
def get_迭代器(self)->迭代器[int]:
返回自迭代器
类SomeContainerProtocol(协议[\u迭代器]):
@抽象方法
定义初始化(self,迭代器:_迭代器):
通过
@抽象方法
def get_迭代器(自)->_迭代器:
通过
_SomeContainer=TypeVar(“”“SomeContainer”,bound='SomeContainerProtocol',协变=True)
类内容(泛型[\u SomeContainer]):
容器:_SomeContainer
定义初始化(self,容器:_SomeContainer):
self.container=容器
def foo(self:Thingy[SomeContainerProtocol[\u Iterator]])->\u Iterator:
通过
def bar(自我)->\u SomeContainer:
通过
thingy=thingy(某个容器(范围(10)。\uuuu iter\uuuuu())
显示类型(thingy)#显示类型为“…thingy[…SomeContainer*]”
显示类型(thingy.foo)#显示类型为'def()->typing.Iterator[builtins.int]'
显示类型(thingy.bar)#显示类型为'def()->…SomeContainer*'
您可以使用一个通用协议(从Python 3.8开始提供)来注释self,以代替您的类型var,然后mypy将推断迭代器的类型。我认为您不能有适当的关联类型,但也许您可以使迭代器成为Thingy上的另一个通用类型参数,并以某种方式约束哪些组合是有效的?