使用普通的之间没有真正的区别typing.Dict
and dict
, no.
However, typing.Dict
is a Generic type https://docs.python.org/3/library/typing.html#generics * 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:
因此,很可能在项目生命周期的某个时刻,您想要更精确地定义字典参数,此时扩展typing.Dict
to typing.Dict[key_type, value_type]
是比替换“更小的”变化dict
.
您可以使用以下方法使其更加通用Mapping https://docs.python.org/3/library/typing.html#typing.Mapping or MutableMapping https://docs.python.org/3/library/typing.html#typing.MutableMapping在这里输入;因为你的函数不需要alter映射,我会坚持Mapping
. A dict
是一种映射,但您可以创建也满足映射接口的其他对象,并且您的函数很可能仍然可以使用这些对象:
def change_bandwidths(new_bandwidths: typing.Mapping[str, str],
user_id: int,
user_name: str) -> bool:
现在你清楚地告诉这个函数的其他用户你的代码实际上不会alter the new_bandwidths
映射传入。
您的实际实现只是期望一个可打印的对象。这可能是一个测试实现,但就目前情况而言,如果您使用,您的代码将继续工作new_bandwidths: typing.Any
,因为Python中的任何对象都是可打印的。
*: Note: If you are using Python 3.7 or newer, you can use dict
as a generic type if you start your module with from __future__ import annotations https://www.python.org/dev/peps/pep-0563/, and as of Python 3.9, dict
(as well as other standard containers) supports being used as generic type even without that directive https://www.python.org/dev/peps/pep-0585/.