假设我想在collect方法中收集并可迭代为另一种类型:
from typing import Generic, TypeVar, Collection
from dataclasses import dataclass
T = TypeVar("T")
@dataclass
class Example(Generic[T]):
data: list[T]
def collect(self, collector: type[Collection]) -> Collection[T]:
return collector(self.data)
如果这样实现,使用哪个收集器的类型提示信息就会丢失:
# result should type-hint 'set[int]'
# but instead shows 'Collection[int]'
# The collector type is lost..
result = Example([1, 2]).collect(set)
如何保留集合的类型和集合所包含内容的类型,同时保持通用?
代替
type[Collection]
,使用 Callable
来指定签名并利用如何推断返回类型:
@dataclass
class Example(Generic[T]):
data: list[T]
def collect(self, collector: Callable[[list[T]], C]) -> C:
return collector(self.data)
example = Example([1, 2])
reveal_type(example.collect(set)) # mypy & pyright => set[int]
reveal_type(example.collect(tuple)) # mypy & pyright => tuple[int, ...]
reveal_type(example.collect(list)) # mypy & pyright => list[int]
reveal_type(example.collect(Example)) # mypy & pyright => Example[int]