使用循环引用为注释类型创建别名时如何避免NameError?

时间:2019-03-28 15:39:57

标签: python python-3.x annotations type-hinting

正如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

我知道使用字符串文字的后备语法,并且确实有效。但是,我很好奇是否可以使用正式可用的新方法。

1 个答案:

答案 0 :(得分:0)

一种技术是使用typing.TYPE_CHECKING constant。该常量在运行时始终为false,但是像mypy这样的类型检查器将其视为始终为true:

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指令或使用字符串文字类型。