可以使用像Dict和List这样的泛型类型提示,没有方括号吗?

时间:2017-12-05 11:36:25

标签: python type-hinting

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是否可以通过这种方式使用?)

1 个答案:

答案 0 :(得分:3)

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

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

  

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

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

这相当于省略了通用符号,只是说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]
相关问题