Python tuple typing

Viewed 31

Let's say I have a numpy array and I get an item from it and want to make it a tuple.

If I assign that item to a variable that expects a specific type, mypy complains that the expression and variable types do not match. If I cast the array item to that specific type, everything works fine.

My question is if there's another way to tell the built-in tuple class what its return type is, instead of using cast.

Here's a simple example:

from typing import cast, Tuple

import numpy as np

Point = Tuple[int, int]

points = np.array([[[1, 1], [2, 2], [3, 3], [4, 4]]])

p1 = points[points.argmin()][0]

p1_tuple: Point = tuple(p1)

mypy throws this error on this snippet:

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

If I change the last line to p1_tuple: Point = cast(Point, tuple(p1)), mypy checks pass with no issue.

So in the case of this example, is cast the only way to tell mypy that tuple(p1) is going to be a Point?

0 Answers
Related