gpt4 book ai didi

python - 如何根据参数类型声明返回类型?

转载 作者:行者123 更新时间:2023-12-04 12:21:55 26 4
gpt4 key购买 nike

这个问题类似于Python Typing: declare return value type based on function argument但足够不同以至于它不适合评论。
我有以下功能:

T = TypeVar('T', dict, str)

def fun(t: T) -> T:
if t == dict:
return {"foo": "bar"}
else:
return "foo"
我希望能够这样称呼它:
a_string = fun(str)
a_dict = fun(dict)
Pylance 在第二行抛出这个错误:
Expression of type "dict[str, str]" cannot be assigned to return type "T@fun"
最后一行出现这个错误:
Expression of type "Literal['foo']" cannot be assigned to return type "T@fun"
根据 this answer ,我应该能够做这样的事情:
T = TypeVar('T', dict, str)

def fun(t: Type[T]) -> T:
if t == dict:
return t({"foo": "bar"})
else:
return t("foo")
这会消除第二行的错误,但会导致最后一行出现不同的错误:
No overloads for "__init__" match the provided arguments
Argument types: (Literal['foo'])
我学习了 this answer在我终于能够使它工作之前很长一段时间:
T = TypeVar('T', dict, str)

def fun(t: Callable[..., T]) -> T:
if t == dict:
return t({"foo": "bar"})
else:
return t("foo")
问题是我不明白它为什么有效。我不明白为什么其他人不这样做。

最佳答案

The problem with this is I don't understand why it works


最后一个有效,因为类型是可调用的。所以这里的输入是 fun接受一些东西,给定一些东西,将返回 T ,然后您以类型的形式提供它。

And I don't understand why the others don't.


第一个版本不行,因为 ->左右两边没有绑定(bind).所以你可以传递一个类型变量,但你不能指定左边的特定必须是右边的特定。换句话说,如果参数是 dict ,然后根据签名,返回类型不必是 dict,而是仍然是 typevar 指定的类型(这有点令人困惑,因为相同的符号 - T - 出现在两者中。但是, T 在这里表示“...之一”)。
第二个版本不起作用,因为 return就类型检查器而言,这表明您也正在返回一个类型。

关于python - 如何根据参数类型声明返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68399417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com