我正在练习在 Python 3.5 中使用类型提示。我的一位同事使用 typing.Dict
:
import typing
def change_bandwidths(new_bandwidths: typing.Dict,
user_id: int,
user_name: str) -> bool:
print(new_bandwidths, user_id, user_name)
return False
def my_change_bandwidths(new_bandwidths: dict,
user_id: int,
user_name: str) ->bool:
print(new_bandwidths, user_id, user_name)
return True
def main():
my_id, my_name = 23, "Tiras"
simple_dict = {"Hello": "Moon"}
change_bandwidths(simple_dict, my_id, my_name)
new_dict = {"new": "energy source"}
my_change_bandwidths(new_dict, my_id, my_name)
if __name__ == "__main__":
main()
它们都工作得很好,似乎没有区别。
我已阅读 typing
module documentation .
在 typing.Dict
或 dict
之间我应该在程序中使用哪一个?
最佳答案
使用纯 typing.Dict
和 dict
并没有真正的区别,没有。
但是,typing.Dict
是 Generic type * 让您也指定键和值的类型,使其更加灵活:
def change_bandwidths(new_bandwidths: typing.Dict[str, str],
user_id: int,
user_name: str) -> bool:
因此,很可能在您的项目生命周期的某个时刻,您希望更精确地定义字典参数,此时将 typing.Dict
扩展为 typing。 Dict[key_type, value_type]
是比替换 dict
更“小的”变化。
您可以使用 Mapping
使其更加通用或 MutableMapping
在这里输入;因为你的函数不需要改变映射,我会坚持使用Mapping
。 dict
是一种映射,但您可以创建其他也满足映射接口(interface)的对象,并且您的函数可能仍然可以使用这些对象:
def change_bandwidths(new_bandwidths: typing.Mapping[str, str],
user_id: int,
user_name: str) -> bool:
现在您清楚地告诉此函数的其他用户,您的代码实际上不会更改传入的 new_bandwidths
映射。
您的实际实现只是期望一个可打印的对象。这可能是一个测试实现,但就目前而言,如果您使用 new_bandwidths: typing.Any
,您的代码将继续工作,因为 Python 中的任何对象都是可打印的。
*:注意:如果您使用 Python 3.7 或更新版本,如果您以 from __future__ import annotations
开头模块,则可以使用 dict
作为泛型类型,并且从 Python 3.9 开始,dict
(以及其他标准容器)supports being used as generic type even without that directive .
关于python - 定义typing.Dict和dict之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37087457/