Type hinting: list of str and/or list of int

Viewed 123

Let's say we have a simple function to print matrices. And we want to warn users that this function works only with list or tuple of lists or tuples containing only strings.

As far as I learned from PEP 484 and PEP 585 the one can use generics such as list and tuple for type hinting of corresponding sequences. Also, the typing syntax with the list generic type requires to use it with the only one argument - the common type of all list elements.

So, I've constructed two type variables as shown below.

But, obviously I didn't fully get the idea. It hadn't raised a warning when I passed to the function the argument contained mixed list of string and list of integers. While I expected it.

Could you please explain me this behaviour.

Row = list[str] | tuple[str, ...]
Matrix = tuple[Row, ...] | list[Row]

def print_matrix(matrix: Matrix, *matrices, right: bool = False) -> None:
    """Prints one or more matrices in line to the stdout."""
    # ...

test_matr1 = [['1', '0', '0'], ['0', '1', '0'], ['0', '0', '1']]
test_matr2 = [[1, 0, 0], ['0', '1', '0'], ['0', '0', '1']]
test_matr3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
print_matrix(test_matr1)
print_matrix(test_matr2)
print_matrix(test_matr3)

Here's what PyCharm shows in the tooltip for the test_matr2:

test_matr2: list[list[int] | list[str]] = [[1, 0, 0], ['0', '1', '0'], ['0', '0', '1']]

While I expected to see the warning, same to the one I've got for test_matr3.

Expected type 'tuple[list[str] | tuple[str, ...], ...] | list[list[str] | tuple[str, ...]]', got 'list[list[int]]' instead

0 Answers
Related