PEP 585 —— 标准集合中的类型提示泛型声称在 Python 3.7 和 3.8 下都具有标准from __future__ import annotations
序言的可用性。尤其:
对于仅限于类型注释的用例,带有
annotations
future-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)