在 if else 中定义类型时,Mypy 引发“无法分配多个类型”

Erf*_*fan 6 python type-hinting mypy

在我们的测试中,我们测试了 numpy 的多个版本。旧版本没有np.random.Generator我们想要在打字中定义的某些类(),因此我选择根据检查 numpy 版本来定义类型:

# random generator
if np_version_under1p17:
    RandomState = Union[int, ArrayLike, np.random.RandomState]
else:
    RandomState = Union[int, ArrayLike, np.random.Generator, np.random.RandomState]
Run Code Online (Sandbox Code Playgroud)

但这会导致:

Cannot assign multiple types to name "RandomState" without an explicit "Type[...]" annotation 
Run Code Online (Sandbox Code Playgroud)

删除if .. else可以解决此错误:

Cannot assign multiple types to name "RandomState" without an explicit "Type[...]" annotation 
Run Code Online (Sandbox Code Playgroud)

但是我们使用旧 numpy 版本的测试将会失败。

定义 的最佳方法是什么RandomState,但是以这样的方式定义它,以便它在我们的测试中既适用于新旧的 numpy 版本。