python - Good way to define new Protocol for collection types - Stack Overflow

admin2025-04-17  2

I would like to define a new structural type for my code that is basically a non-mutable, ordered set.

The following code captures the gist of it

from ordered_set import OrderedSet
from typing import Protocol, TypeVar

from collections.abc import Set, Sequence

T = TypeVar("T", covariant=True)


class ConstOrderedSet(Protocol, Set[T], Sequence[T]):  # type: ignore[misc]
    pass


x: ConstOrderedSet[int] = OrderedSet([1, 2, 3])


x.append(5) # correctly fails
x[1] # correctly passes
x[1] = 2  # correctly fails

and correctly accepts/rejects valid/invalid constructs. But apparently only Protocols are allowed in the inheritance tree of Protocols and apparently Set and Sequence are not Protocols. The code does with mypy what I want, but I wonder how to do it correctly without having to implement a full Protocol of ConstOrderedSet on my own.

转载请注明原文地址:http://anycun.com/QandA/1744894804a89137.html