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?
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.
'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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With