提问人:makpia 提问时间:6/14/2023 最后编辑:makpia 更新时间:6/14/2023 访问量:96
如何在Python中注释具有泛型类型的泛型类型?
how to annotate a generic type that has a generic type in python?
问:
我正在编写一个模仿 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)
a
list[Any]
list[int]
有没有办法把它写成这样?a = my_iter([1, 2, 3]).collect(list[int])
我知道我可以添加注释给 like.但这将停止链接并引入一个新名称。并将注解移动到返回类型将使其不起作用:a
a: list[int] = ...
def foo() -> list[int]:
return my_iter([1, 2, 3]).collect(list)
我写这个类的原因是像在 Rust 中一样使用链式来模拟我的代码。像 list 和 dict 这样的基本类型没有像 和 这样的方法,这使得编辑代码变得非常痛苦(回到代码块的开头,添加很远的 parens,额外的缩进,转到文件顶部并每次添加,...my_iter
filter
map
from itertools import ...
就在我写下所有这些描述之后,我发现已经支持这样写:
a = my_iter([1, 2, 3]).collect(list[int])
哈哈
答: 暂无答案
评论