How to get Mypy to realize that sorting two ints gives back two ints

人走茶凉 提交于 2020-06-17 01:57:32

问题


My code is as follows:

from typing import Tuple

a: Tuple[int, int] = tuple(sorted([1, 3]))

Mypy tells me:

Incompatible types in assignment (expression has type "Tuple[int, ...]", variable has type "Tuple[int, int]")

What am I doing wrong? Why can't Mypy figure out that the sorted tuple will give back exactly two integers?


回答1:


The call to sorted produces a List[int] which carries no information about length. As such, producing a tuple from it also has no information about the length. The number of elements simply is undefined by the types you use.

You must tell your type checker to trust you in such cases. Use # type: ignore or cast to unconditionally accept the target type as valid:

# ignore mismatch by annotation
a: Tuple[int, int] = tuple(sorted([1, 3]))  # type: ignore
# ignore mismatch by cast
a = cast(Tuple[int, int], tuple(sorted([1, 3])))

Alternatively, create a lenght-aware sort:

 def sort_pair(a: T, b: T) -> Tuple[T, T]:
     return (a, b) if a < b else (b, a)


来源:https://stackoverflow.com/questions/56471335/how-to-get-mypy-to-realize-that-sorting-two-ints-gives-back-two-ints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!