键入:class 继承期间推断的类型过于笼统

Typing: Inferred type too general during class inheritance

我面临以下问题。假设我想为 Dataset 及其 Sample 定义泛型 class。然后,我想创建这些最终将被实例化的特定子 classes(例如 DatasetOfSpecificSamples 包含 MoreSpecificSample 样本)。为了节省一些 LoC,我想在 Dataset class.

中实现常用功能

但是,我无法正确获取继承子类中的类型提示。他们太笼统了。请参阅以下示例,我希望 __iter__ return 类型的 DatasetOfSpecificSamples 将是 MoreSpecificSample,但 MyPy 仅推断 Sample.

有没有办法在不重新定义方法本身的情况下强制执行更具体提示?

from typing import Mapping, Iterator

class Sample:
    pass


class MoreSpecificSample(Sample):
    pass


class Dataset:
    def __init__(self, samples: Mapping[str, Sample]):
        self.samples = samples

    def __iter__(self) -> Iterator[Sample]:
        yield from self.samples.values()


class DatasetOfSpecificSamples(Dataset):
    samples: Mapping[str, MoreSpecificSample]

    # def __iter__(self) -> Iterator[CommonCriteriaCert]: <-- This fixes the problem, as it specifies the type
    #     yield from self.certs.values()

dset = DatasetOfSpecificSamples()
for sample in dset: # <-- the inferred type of "sample" is Sample, not MoreSpecificSample
    pass

使 Dataset class 通用:

T = TypeVar("T")

class Dataset(Generic[T]):

    def __init__(self, samples: Mapping[str, T]):
        self.samples = samples

    def __iter__(self) -> Iterator[T]:
        yield from self.samples.values()


class DatasetOfSpecificSamples(Dataset[MoreSpecificSample]):
    samples: Mapping[str, MoreSpecificSample]