作为this great answer建议,从 Python 3.7 开始,如果
from __future__ import annotations
使用指令。
但是,如果我想为注释类型创建别名,这仍然不起作用:
from __future__ import annotations
import typing
MyType1 = typing.Union[str, MyType2]
MyType2 = typing.Mapping[str, MyType1]
这仍然给我 NameError: name 'MyType2' is not defined
我知道使用字符串文字的回退语法,它确实有效。但是,我很好奇是否有可能以某种方式使用正式可用的新方法。
最佳答案
一种技术是使用 typing.TYPE_CHECKING
constant .此常量在运行时始终为假,但被类型检查器(如 mypy)视为始终为真:
from __future__ import annotations
from typing import TYPE_CHECKING, Union, Mapping
if TYPE_CHECKING:
MyType1 = Union[str, MyType2]
MyType2 = Mapping[str, MyType1]
由于此常量在运行时为 False,Python 永远不会尝试评估任何一种类型别名,这让您可以避免 NameError。
当然,您需要使用 from __future__ import annotations
指令或使用字符串文字类型。
关于python - 使用循环引用为注释类型创建别名时如何避免 NameError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55401633/