如何在类型化签名(Python > 3.9)中指定一个需要更新方法的通用 MutableSet?

发布于 2025-01-20 09:37:59 字数 866 浏览 3 评论 0原文

我写了一个库。它的一些函数和方法在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳若烟 2025-01-27 09:37:59

@SUTerliakov 的评论回答了问题,我能够这样解决问题:

正确且类型安全的解决方案是通用协议[T],它定义了所有
设置您需要的方法。如果只有5-6种方法,也够方便了。 –
苏特尔利亚科夫
4月12日 19:34

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文