小编Cec*_*rry的帖子

PEP 585 在 Python 3.7 和 3.8 下在运行时不可用吗?

PEP 585 —— 标准集合中的类型提示泛型声称在 Python 3.7 和 3.8 下都具有标准from __future__ import annotations序言的可用性。尤其:

对于仅限于类型注释的用例,带有annotationsfuture-import(自 Python 3.7 起可用)的Python 文件可以参数化标准集合,包括内置函数。

从 Python 3.7 开始,from __future__ import annotations使用时,函数和变量注释可以直接参数化标准集合。例子:

from __future__ import annotations

def find(haystack: dict[str, list[int]]) -> int:
    ...
Run Code Online (Sandbox Code Playgroud)

虽然上面的玩具示例技术上进行了解析,但仅此而已。在 Python 3.7 或 3.8 下尝试在运行时实际使用参数化的内置集合总是会引发可怕的TypeError: 'type' object is not subscriptable异常:

>>> def find(haystack: dict[str, list[int]]) -> int: pass
>>> print(find.__annotations__)
{'haystack': 'dict[str, list[int]]', 'return': 'int'}
>>> eval(find.__annotations__['haystack'])
TypeError: 'type' object is not subscriptable …
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-typing pep585

13
推荐指数
1
解决办法
988
查看次数

标签 统计

pep585 ×1

python ×1

python-3.x ×1

python-typing ×1