对列表使用类型提示时 Pytest 失败

Pytest fails when using type hints for lists

如果我提供准确的输入:

def _get_options(self, property_options: list[dict]) -> list[OptionInput]:

pytest (v.6.2.5, Python 3.7.3) returns 错误:

E TypeError: 'type' object is not subscriptable

所有类型的列表都会出现这种情况:list[str], list[dict],等等

但是当我将 header 更改为:

def _get_options(self, property_options: list) -> list:

有效。与文字相同:

配置中是否有任何选项允许 list[dict] 等类型提示?谢谢!

您正在寻找from __future__ import annotations;您可以将其添加到模块的顶部。

需要注意的是,这不适用于 Python 3.9 之前的版本中的直接赋值,例如 CustomType = list[dict]


您还可以在 PEP 上阅读更多内容,其中将 __future__ 导入 Python 3.7+。