如何将 "typing_extensions.Literal" 绑定到另一个模块,以便它可以从该模块导入?

How to bind "typing_extensions.Literal" into another module so that it can be imported from that module?

为了减少导入次数,我尝试在专用模块中绑定一些输入别名,例如colour.utilities.hints.

在该模块中,出于兼容性原因以及我仍然是 运行 Python 3.7,我尝试将 typing_extensions.Literal 绑定到一个新的 Literal 属性:

colour/utilities/hints.py

import typing_extensions

Literal = typing_extensions.Literal

然后我使用绑定属性如下:

colour/utilities/array.py

from typing import Optional, Union

from colour.utilities.hints import ArrayLike, NDArray, Literal

# ...

def orient(a: ArrayLike,
           orientation: Literal['Flip', 'Flop', '90 CW', '90 CCW', '180']
           ) -> Union[NDArray, None]:
    orientation = validate_method(orientation,
                                  ['Flip', 'Flop', '90 CW', '90 CCW', '180'])

    if orientation == 'flip':
        return np.fliplr(a)
    elif orientation == 'flop':
        return np.flipud(a)
    elif orientation == '90 cw':
        return np.rot90(a, 3)
    elif orientation == '90 ccw':
        return np.rot90(a)
    elif orientation == '180':
        return np.rot90(a, 2)
    else:
        return None

当我输入时检查模块:

colour/utilities/array.py:1077: error: Variable "colour.utilities.hints.Literal" is not valid as a type
colour/utilities/array.py:1077: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
colour/utilities/array.py:1077: error: Name "Flip" is not defined
colour/utilities/array.py:1077: error: Name "Flop" is not defined
colour/utilities/array.py:1077: error: Invalid type comment or annotation

colour/utilities/array.py中导入typing_extensions.Literal并直接使用它是可以的。

修改来自

的绑定
import typing_extensions

Literal = typing_extensions.Literal

from typing_extensions import Literal

Literal = Literal

解决了问题,但我不完全确定原因。

只是一个稍微改进的建议,但您不需要显式定义新的 Literal 变量。例如,您还可以按如下方式定义 hints.py 模块:

__all__ = [
    'Literal',
    # ...
]

try:
    from typing_extensions import Literal
except ImportError:
    from typing import Literal

然后在另一个模块中:

from hints import Literal