I have written a library. Some of its functions and methods operate on sets of Hashables, e.g.:

def some_function(my_set: set[Hashable]) -> None:
    ...
    my_set.update(...)
    ...

How can I define something like an UpdatableSet (and use it instead of "set" in the signature of some_function), that demands existence of an update method, but allows for using some other class (from an external library) than set, that provides all necessary methods, in function calls?

def some_function(my_set: UpdatableSet[Hashable]) -> None:
    ...
    my_set.update(...)
    ...

from intbitset import intbitset  # see PyPI
some_set = intbitset(rhs=100)
some_function(some_set)

MutableSet[Hashable] is not enough, since it does not guarantee that there is an update method.

I use MyPy for type checking.


I thought of something like the following, but the register method is not found. And I do not know, if this is the right approach. Maybe defining some generic protocol would be the right way.

class UpdatableSet(MutableSet[_T], Generic[_T], ABC):
    def update(self, other) -> None:
        pass

UpdatableSet.register(set)
UpdatableSet.register(intbitset)
1

There are 1 answers

0
HeWeMel On

The comment of @SUTerliakov answers the question, and I was able to solve the problem this way:

The proper and type-safe solution would be generic Protocol[T] that defines all methods of set you need. If there's only 5-6 methods, it's also convenient enough. – SUTerliakov Apr 12 at 19:34