如何在类型化签名(Python > 3.9)中指定一个需要更新方法的通用 MutableSet?
我写了一个库。它的一些函数和方法在 Hashable 集合上运行,例如:
def some_function(my_set: set[Hashable]) -> None:
...
my_set.update(...)
...
如何定义像 UpdatableSet 这样的东西(并使用它而不是 some_function 签名中的“set”),要求是否存在更新方法,但允许使用 set 以外的其他类(来自外部库),在函数调用中提供所有必要的方法?
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] 还不够,因为它不保证有更新方法。
我使用 MyPy 进行类型检查。
我想到了类似下面的东西,但没有找到注册方法。我不知道这是否是正确的方法。也许定义一些通用协议是正确的方法。
class UpdatableSet(MutableSet[_T], Generic[_T], ABC):
def update(self, other) -> None:
pass
UpdatableSet.register(set)
UpdatableSet.register(intbitset)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@SUTerliakov 的评论回答了问题,我能够这样解决问题:
The comment of @SUTerliakov answers the question, and I was able to solve the problem this way: