Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can mypy handle list comprehensions?

from typing import Tuple
def test_1(inp1: Tuple[int, int, int]) -> None:
    pass

def test_2(inp2: Tuple[int, int, int]) -> None:
    test_tuple = tuple(e for e in inp2)
    reveal_type(test_tuple)
    test_1(test_tuple)

While running mypy on the above code, I get:

error: Argument 1 to "test_1" has incompatible type "Tuple[int, ...]"; expected "Tuple[int, int, int]"

Is test_tuple not guaranteed to have 3 int elements? Does mypy not handle such list comprehensions or is there another way of defining the type here?

like image 546
alkamid Avatar asked Feb 27 '18 12:02

alkamid


People also ask

Is list comprehension faster than for loop Julia?

For Loops are Faster than List Comprehensions. Suppose we only want to perform some computations (or call an independent function multiple times) and do not want to create a list. In that case, we see that the list comprehension is 25% slower than the for loop.

Are Python list comprehensions lazy?

'Lazy lists' are called generators in Python. Just use (...) Instead of [...] in your example. I'm aware of generator expressions, but the fact that list comprehensions are not lazy can trip people if they are used to other languages with this feature, since they are usually lazy.

Is list comprehension faster than map Python?

Map function is faster than list comprehension when the formula is already defined as a function earlier. So, that map function is used without lambda expression.

Is list comprehension faster than filter Python?

For large lists with one million elements, filtering lists with list comprehension is 40% faster than the built-in filter() method. What is this? The reason is the efficient implementation of the list comprehension statement.


1 Answers

As of version 0.600, mypy does not infer types in such cases. It would be hard to implement, as suggested on GitHub.

Instead, we can use cast (see mypy docs):

from typing import cast, Tuple

def test_1(inp1: Tuple[int, int, int]) -> None:
    pass

def test_2(inp2: Tuple[int, int, int]) -> None:
    test_tuple = cast(Tuple[int, int, int], tuple(e for e in inp2))
    reveal_type(test_tuple)
    test_1(test_tuple)
like image 192
alkamid Avatar answered Oct 02 '22 16:10

alkamid