问题:定义type.Dict和dict之间的区别?

我正在练习在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模块文档

之间typing.Dictdict哪一个,我应该在程序中使用?

I am practicing using type hints in Python 3.5. One of my colleague uses 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()

Both of them work just fine, there doesn’t appear to be a difference.

I have read the typing module documentation.

Between typing.Dict or dict which one should I use in the program?


回答 0

使用Plaintyping.DictdictNo之间没有真正的区别。

然而,typing.Dict是一种通用型 *,可让您指定键和值的类型太多,使之更加灵活:

def change_bandwidths(new_bandwidths: typing.Dict[str, str],
                      user_id: int,
                      user_name: str) -> bool:

因此,很可能是在项目生命周期中的某个时候,您希望更精确地定义字典参数,在这一点上,扩展typing.Dicttyping.Dict[key_type, value_type]而不是替换是“更小的”改变dict

您可以通过在此处使用类型来使其更通用。由于您的函数不需要更改映射,因此我坚持使用Mapping。Adict是一个映射,但是您可以创建也满足映射接口的其他对象,并且您的函数可能仍可以与那些对象一起使用:

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或更高版本,则使用dict开头的模块即可将其用作通用类型from __future__ import annotations,而从python 3.9开始,dict(以及其他标准容器)也支持将其用作通用类型。指令

There is no real difference between using a plain typing.Dict and dict, no.

However, typing.Dict is a Generic type that lets you specify the type of the keys and values too, making it more flexible:

def change_bandwidths(new_bandwidths: typing.Dict[str, str],
                      user_id: int,
                      user_name: str) -> bool:

As such, it could well be that at some point in your project lifetime you want to define the dictionary argument a little more precisely, at which point expanding typing.Dict to typing.Dict[key_type, value_type] is a ‘smaller’ change than replacing dict.

You can make this even more generic by using or types here; since your function doesn’t need to alter the mapping, I’d stick with Mapping. A dict is one mapping, but you could create other objects that also satisfy the mapping interface, and your function might well still work with those:

def change_bandwidths(new_bandwidths: typing.Mapping[str, str],
                      user_id: int,
                      user_name: str) -> bool:

Now you are clearly telling other users of this function that your code won’t actually alter the new_bandwidths mapping passed in.

Your actual implementation is merely expecting an object that is printable. That may be a test implementation, but as it stands your code would continue to work if you used new_bandwidths: typing.Any, because any object in Python is printable.


回答 1

是以下内容的通用版本dict

class typing.Dict(dict, MutableMapping[KT, VT])

dict的通用版本。此类型的用法如下:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
     return word_list[word]

在这里,您可以在dict中指定键和值的类型: Dict[str, int]

is a generic version of dict:

class typing.Dict(dict, MutableMapping[KT, VT])

A generic version of dict. The usage of this type is as follows:

def get_position_in_index(word_list: Dict[str, int], word: str) -> int:
     return word_list[word]

Here you can specify the type of key and values in the dict: Dict[str, int]


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。