【发布时间】:2021-07-17 00:22:32
【问题描述】:
这个问题与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")
这个问题是我不明白为什么它有效。我不明白为什么其他人不这样做。
【问题讨论】:
-
t是指dict/str类型的对象,还是字面意义上的类型本身?即你打电话给fun({})还是fun(dict)? -
@0x5453 好问题。我更新了我的问题以澄清。
-
另外,什么版本的 Python?在 3.9 中,它们允许使用内置类型作为容器的类型提示(例如,您可以使用
list[int]而不是typing.List[int]),所以我想知道这对您所看到的内容是否有任何影响。 -
@0x5453 我现在卡在 3.8 上。
标签: python python-typing