python - 定义typing.Dict和dict之间的区别?

标签 python dictionary type-hinting python-typing

我正在练习在 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.Dictdict 之间我应该在程序中使用哪一个?

最佳答案

使用纯 typing.Dictdict 并没有真正的区别,没有。

但是,typing.DictGeneric 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在这里输入;因为你的函数不需要改变映射,我会坚持使用Mappingdict 是一种映射,但您可以创建其他也满足映射接口(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/

相关文章:

python - 使用字典进行翻译 (Python)

python - 如何为 Mypy 类型注释指定 OrderedDict K,V 类型?

python - 有没有办法将 sqlalchemy 查询中的数据附加到 for 循环内的 pandas 数据框中?

python - 比较序列 Python

python - 如何在Python中生成稀疏正交矩阵?

python - python 代码片段的解释 >>numpy.nonzero(row == max(row))[0][0]<< 来自使用 numpy 的脚本

java - 在不知道 Java 类名称的情况下调用类构造函数

python - 使用python函数在字典中按值获取键并返回键或 "None'

python - 是否可以在 python 中对已编译的正则表达式进行类型提示?

python - 如何使用类型提示为参数指定多种类型?