i am writing a iter type imitating the iterator in rust, which has a .collect() method:
# 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: ...
the problem is when i write a = my_iter([1, 2 ,3]).collect(list), the type of a will be analyzed as list[Any]. what i want is to let type checker know this is list[int] instead.
is there a way to write it like a = my_iter([1, 2, 3]).collect(list[int]) ?
i know i can add annotation to a like a: list[int] = .... but this will stop the chaining and introduce a new name. and move the annotation to return type will make it not working:
def foo() -> list[int]:
return my_iter([1, 2, 3]).collect(list)
the reason i write this my_iter class is to similify my code by using chain style just like in rust. basic types like list and dict do not have methods like filter and map, which makes it such a pain to edit codes(go back to the beginning of code blocks, add parens which is far away, extra indentation, go to the top of file and add from itertools import ... everytime, ...).
just after i wrote down all these descriptions, i found it is already supported to write it like:
a = my_iter([1, 2, 3]).collect(list[int])
lol