Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...