python variadic的类型提示,其返回类型取决于参数类型
考虑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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论