如何在Python中注释具有泛型类型的泛型类型?

how to annotate a generic type that has a generic type in python?

提问人:makpia 提问时间:6/14/2023 最后编辑:makpia 更新时间:6/14/2023 访问量:96

问:

我正在编写一个模仿 Rust 中的迭代器的 ITER 类型,它有一个 .collect() 方法:

# python 3.11

from typing import TypeVar, Generic, Self
from collections.abc import Iterator

T = TypeVar('T')
R = TypeVar('R')

class my_iter(Generic[T]):
    def __init__(self, obj) -> None:
        self.obj = obj
        self.iter = iter(obj)
    def __iter__(self) -> Iterator[T]:
        return self
    def __next__(self) -> T:
        return next(self.iter)
    def collect(self, astype: type[R]) -> R:
        return astype(self.obj)
    ...
    def _other_methods_in_chaining_style(self) -> Self: ...

问题是当我写的时候,类型会被分析为。我想要的是让类型检查器知道这是。a = my_iter([1, 2 ,3]).collect(list)alist[Any]list[int]

有没有办法把它写成这样?a = my_iter([1, 2, 3]).collect(list[int])

我知道我可以添加注释给 like.但这将停止链接并引入一个新名称。并将注解移动到返回类型将使其不起作用:aa: list[int] = ...

def foo() -> list[int]:
    return my_iter([1, 2, 3]).collect(list)

我写这个类的原因是像在 Rust 中一样使用链式来模拟我的代码。像 list 和 dict 这样的基本类型没有像 和 这样的方法,这使得编辑代码变得非常痛苦(回到代码块的开头,添加很远的 parens,额外的缩进,转到文件顶部并每次添加,...my_iterfiltermapfrom itertools import ...

就在我写下所有这些描述之后,我发现已经支持这样写:

a = my_iter([1, 2, 3]).collect(list[int])

哈哈

Python 泛型类型 提示 方法链接

评论

0赞 Daniil Fajnberg 6/14/2023
如果您认为这个问题和您自己找到的答案可能会使其他读者受益,您可以改写您的问题,删除解决方案,并自行将解决方案作为答案发布在这里。如果您认为这对其他任何人都没有用,可以删除您的问题。

答: 暂无答案