python variadic的类型提示,其返回类型取决于参数类型

发布于 2025-02-10 04:42:27 字数 822 浏览 1 评论 0原文

考虑Inner_join的定义下面:

from typing import TypeVar
from collections.abc import Mapping, Hashable
from functools import reduce

K = TypeVar('K', bound=Hashable)
V = TypeVar('V')

def keyset(m: Mapping[K, Any]) -> set[K]:
    return set(m.keys())

def inner_join(*ms: Mapping[K, Any]) -> dict[K, tuple[...]]:
    keys = reduce(set.intersection, map(keyset, ms)) if ms else set()

    return {k: tuple(m[k] for m in ms) for k in keys}

我的理解是innit_join的类型提示是正确的,但它比它的特定性要少得多,只要我能以某种方式表达事实元组的元素的类型是由映射ms的值类型修复的。例如,如果我声明了此功能的两个ARG版本,我会写下以下类型:

U = TypeVar('U')
V = TypeVar('V')

def inner_join2(m1: Mapping[K, U], m2: Mapping[K, V]) -> dict[K, tuple[U, V]]:
   ...

是否有任何方法可以概括该注释,以便它适用于variadic版本?

Consider the definition of inner_join below:

from typing import TypeVar
from collections.abc import Mapping, Hashable
from functools import reduce

K = TypeVar('K', bound=Hashable)
V = TypeVar('V')

def keyset(m: Mapping[K, Any]) -> set[K]:
    return set(m.keys())

def inner_join(*ms: Mapping[K, Any]) -> dict[K, tuple[...]]:
    keys = reduce(set.intersection, map(keyset, ms)) if ms else set()

    return {k: tuple(m[k] for m in ms) for k in keys}

My understanding is the type hint for inner_join is correct, but it is much less specific than it could be, provided I could somehow express the fact that the types of the elements of the tuple is fixed by the types of the values of the mappings ms. For instance, if I were declaring a two-arg version of this function, I would write the type as follows:

U = TypeVar('U')
V = TypeVar('V')

def inner_join2(m1: Mapping[K, U], m2: Mapping[K, V]) -> dict[K, tuple[U, V]]:
   ...

Is there any way to generalize that annotation so it works for the variadic version?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文