gpt4 book ai didi

python - 像 Dict 和 List 这样的通用类型提示可以不用方括号而直接使用吗?

转载 作者:行者123 更新时间:2023-11-30 22:25:02 25 4
gpt4 key购买 nike

Dict 上的文档显示它被用作泛型类型,如下所示:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
return word_list[word]

当然,将上面的 word_list 类型提示为 dict 也是正确的:

def get_position_in_index(word_list: dict, word: str) -> int:
return word_list[word]

但是使用 Dict 作为类型提示来指示具有任何类型的键和值的 dict 是否正确?

def get_position_in_index(word_list: Dict, word: str) -> int:
return word_list[word]

(同样,其他泛型类型如 ListSequence 是否可以以这种方式直接使用?)

最佳答案

是的,Dict 被视为 Dict[Any, Any] 的别名。 (dict 也是 Dict[Any, Any] 的别名)。

任何泛型类型都是如此,无论是内置类型还是自定义类型:如果省略类型参数,它们始终默认为 Any。这在 Generics section of PEP 484 中指定。 (强调):

Additionally, Any is a valid value for every type variable. Consider the following:

def count_truthy(elements: List[Any]) -> int:
return sum(1 for elem in elements if element)

This is equivalent to omitting the generic notation and just saying elements: List.

也就是说,我认为一般建议是您应该完全写出 Dict[Any, Any] 而不是仅使用 Dict -- explicit is better then implicit ,等等。

唯一的缺点是你的函数类型签名现在更长了。但我们可以通过使用类型别名来解决这个问题:

from typing import Dict, Any

AnyDict = Dict[Any, Any]
WordDict = Dict[str, int]

# Equivalent to your first code sample
def get_position_in_index_1(word_list: WordDict, word: str) -> int:
return word_list[word]

# Equivalent to your second and third code samples
def get_position_in_index_2(word_list: AnyDict, word: str) -> int:
return word_list[word]

关于python - 像 Dict 和 List 这样的通用类型提示可以不用方括号而直接使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47652666/

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