何时/为何使用类型模块中的类型作为类型提示

问题描述 投票:0回答:2

类型提示的“正确”方式到底是什么? 我的 IDE(和生成的代码)使用以下任一选项可以很好地进行类型提示,但某些类型可以从输入模块导入。与内置函数(如列表或字典)相比,是否更喜欢使用从打字模块导入的内容?

示例:

from typing import Dict
def func_1(arg_one: Dict) -> Dict:
    pass

def func_2(arg_one: dict) -> dict:
    pass
python python-typing
2个回答
12
投票

“正确”的方法是尽可能使用内置函数(例如

dict
超过
typing.Dict
)。仅当您将 Python
typing.Dict
与内置函数一起使用时才需要 < 3.9. In older versions you couldn't use generic annotations like
dict[str, Any]
,您必须使用
Dict[str, Any]
。请参阅PEP 585


3
投票

typing.Dict
dict
之间没有太大区别。

Just

typing.Dict
实际上是通用类型,因此它允许您在括号内指定子类型。

喜欢:

from typing import Dict
def func_1(arg_one: Dict[str, int]) -> Dict:
    pass

但是

typing.Dict
仅当您的 Python 版本低于 3.9 时才需要。否则,您可以对常规
dict
执行相同操作。

示例 Python >= 3.9:

def func_1(arg_one: dict[str, int]) -> dict:
    pass
© www.soinside.com 2019 - 2024. All rights reserved.