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

Mar*_*ery 3 python type-hinting

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

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
    return word_list[word]
Run Code Online (Sandbox Code Playgroud)

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

def get_position_in_index(word_list: dict, word: str) -> int:
    return word_list[word]
Run Code Online (Sandbox Code Playgroud)

Dict但是,像这样单独用作类型提示来指示dict具有任何类型的键和值的a是否正确?

def get_position_in_index(word_list: Dict, word: str) -> int:
    return word_list[word]
Run Code Online (Sandbox Code Playgroud)

(同样,其他泛型类型如List和可以Sequence以这种方式裸露使用吗?)

Mic*_*x2a 5

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

任何泛型类型都是这种情况,无论是内置类型还是定制类型:如果省略类型参数,它们总是默认为Any. 这是在PEP 484 的泛型部分中指定的(添加了强调):

此外,Any是每个类型变量的有效值。考虑以下:

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

这相当于省略通用符号而只说elements: List.

也就是说,我认为一般建议是您应该完全写出来,Dict[Any, Any]而不是仅仅使用Dict--显式比隐式更好,等等。

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

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]
Run Code Online (Sandbox Code Playgroud)