像 Dict 和 List 这样的泛型类型提示可以在没有方括号的情况下直接使用吗?
Can generic type hints like Dict and List be used bare, without square brackets?
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]
(同样,其他泛型类型如 List
和 Sequence
也可以这样使用吗?)
是的,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]
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]
(同样,其他泛型类型如 List
和 Sequence
也可以这样使用吗?)
是的,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]