输入提示集合的类型和集合本身

问题描述 投票:0回答:1

假设我想在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)

如何保留集合的类型和集合所包含内容的类型,同时保持通用?

python generics type-hinting
1个回答
0
投票

代替

type[Collection]
,使用
Callable
来指定签名并利用如何推断返回类型:

(游乐场链接:mypyPyright

@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]
© www.soinside.com 2019 - 2024. All rights reserved.