Python 定义 types.Dict 和 dict 之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37087457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:48:29  来源:igfitidea点击:

Difference between defining typing.Dict and dict?

pythondictionarytype-hinting

提问by Sarit

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

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

两者都工作得很好,似乎没有区别。

I have read the typingmodule documentation.

我已阅读typing模块文档

Between typing.Dictor dictwhich one should I use in the program?

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

回答by Martijn Pieters

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

使用普通typing.Dict和没有真正的区别dict,没有。

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

然而,typing.Dict是一个泛型类型,让你指定键和值的类型太多,使之更加灵活:

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.Dictto typing.Dict[key_type, value_type]is a 'smaller' change than replacing dict.

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

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

您可以通过在此处使用MappingMutableMapping类型使其更加通用;由于您的函数不需要更改映射,因此我会坚持使用Mapping. Adict是一种映射,但是您可以创建其他也满足映射接口的对象,并且您的函数可能仍然可以使用这些对象:

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 alterthe new_bandwidthsmapping passed in.

现在你清楚地告诉这个函数的其他用户你的代码实际上不会改变new_bandwidths传入的映射。

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.

您的实际实现只是期望一个可打印的对象。这可能是一个测试实现,但就目前而言,如果您使用new_bandwidths: typing.Any,您的代码将继续工作,因为 Python 中的任何对象都是可打印的。

回答by AKS

typing.Dictis a generic version of dict:

typing.Dict是一个通用版本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]

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]

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

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