Mypy raises "Cannot assign multiple types" when defining type in if else

Viewed 683

In our tests we test for multiple versions of numpy. The older versions don't have certain classes (np.random.Generator) which we want to define in our typing, so I chose to define the type based on checking the numpy version:

# random generator
if np_version_under1p17:
    RandomState = Union[int, ArrayLike, np.random.RandomState]
else:
    RandomState = Union[int, ArrayLike, np.random.Generator, np.random.RandomState]

But this results in:

Cannot assign multiple types to name "RandomState" without an explicit "Type[...]" annotation 

While removing the if .. else resolves this error:

RandomState = Union[int, ArrayLike, np.random.Generator, np.random.RandomState]

But then our tests with old numpy versions will fail.

What is the best way to define RandomState, but define it in such a way so it will both work for newer and older numpy versions in our tests.

0 Answers
Related