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

问题描述 投票:0回答:1

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

我知道使用字符串文字的回退语法,它确实有用。但是,我很好奇是否可以使用正式可用的新方法。

python python-3.x annotations type-hinting
1个回答
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指令或使用字符串文字类型。

© www.soinside.com 2019 - 2024. All rights reserved.