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 Protocol
s are allowed in the inheritance tree of Protocol
s 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.