Python Typehints:泛型对实现非泛型接口有约束

时间:2020-01-21 09:50:56

标签: python generics type-hinting

请考虑以下设置:

  • 实施通用的MutableSequence,该通用__init__可以在其MutableSequence中定义如何访问某些键属性以在运行时执行一致性检查(例如:在class UniqueKeyedList(MutableSequence[T], collections.abc.MutableSequence): """A mutable sequence that maintains uniqueness of a key-property accessible through a determined selector function. Args: contents (Collection[T]): A collection of items to initialise the `UniqueKeyedList` with. key_getter (Callable[[T], Hashable]): Getter function to access key properties of `contents` items. Raises: ValueError: Raised if the input `contents` do not fulfill the uniqueness of keys property. """ def __init__(self, contents: Collection[T], *, key_getter=Callable[[T], Hashable]): if not _fulfills_uniqueness_property(values=contents, key_getter=key_getter): raise ValueError("Collection must not contain multiple entries with same key.") self._contents = list(contents) self._key = key_getter # other implementations for abstract methods here 中强制键属性的唯一性)
UniqueKeyedList
  • 用固定的key_getter子类化UniqueKeyedList,并要求key_getter中的所有项目必须实现一个接口,以确保class IDIdentifiable(ABC): """Interface for objects implementing an `id_` property returning a hashable value. """ @property @abstractmethod def id_(self) -> Hashable: raise NotImplementedError class IDUniqueItemList(UniqueKeyedList[IDIdentifiable]): """`UniqueKeyedList` composed of `IDIdentifiable` objects. Args: args (Collection[IDIdentifiable]): A collection of `IDIdentifiable` objects to initialise the unique item list with. Raises: ValueError: Raised if any operation violates the unique key constraint. """ def __init__(self, args: Collection[IDIdentifiable]): super().__init__(args, key_getter=lambda x: x.id_) 始终访问现有属性:< / li>
IDUniqueItemList

目标:我想将IDUniqueItemList[MyClassImplementingIDIdentifiable]保留为通用类,以便为存储在其中的各个元素设置类型提示(例如IDUniqueItemList)。但是,我不能仅仅使TypeVar通用而不能强制我使用的IDIdentifiable实现IDIdentifiable。使IDUniqueItemList通用似乎是错误的。

如何最好地实现这样的设置,以保持子类{{1}}的通用性?

0 个答案:

没有答案