TypeVarTuple to get a tuple of lists of unknown types: tuple[*list[Ts]]
?
#1361
Replies: 2 comments 1 reply
-
Hello! When typing star-args, the type hint after from typing import TypeVar
T = TypeVar("T")
def process_lists(*lists: list[T]): ... if you expect a tuple and not star-args, you can still type this like the following (see mypy docs): from typing import TypeVar
T = TypeVar("T")
def process_lists(lists: tuple[list[T], ...]): ... I created a Pyright playground and a mypy playground to show the different possibilities. You can click on the |
Beta Was this translation helpful? Give feedback.
-
In your examples, Mypy is correctly highlighting errors at lines 10 and 18. This is because the signature of T = TypeVar("T")
def f(*args: list[T]) -> T: ... means "a function that accepts arguments of type My question is, however, not about I want to annotate a function that takes lists of different types. For this, I want to annotate type that's contained within a list using This is an expanded example: from typing import TypeVarTuple
Ts = TypeVarTuple("Ts")
def get_first_elements(*args: *list[Ts]) -> tuple[*Ts]:
return tuple(l[0] for l in args)
first_elems = get_first_elements([1, 2, 3], ['a', 'b', 'c'])
print(first_elems) # (1, 'a')
reveal_type(first_elems) # tuple[int, str] And here's an example I've met in a wild: class Parser(Generic[T]):
def parse(self, s: str) -> T: ...
class IntParser(Parser[int]): ...
class StrParser(Parser[str]): ...
class TupleParser(Parser[tuple[*Ts]], Generic[*Ts]):
def __init__(self, *args: *Parser[Ts]): ...
def parse(self, s: str) -> tuple[*Ts]: ...
result = TupleParser(IntParser(), StrParser()).parse('1 a')
print(result) # (1, 'a')
reveal_type(result) # tuple[int, str] |
Beta Was this translation helpful? Give feedback.
-
Hi!
Here's a use-case I got recently: I want to accept a tuple of lists, but I don't know beforehand how many lists there will be, or of what type their elements will be.
Here's the equivalent of what I want in C++:
From what I gather, there's no way to type such function in python:
I wonder if it's something that people are interested in discussing/implementing. Maybe there are existing discussions that I can help with? I haven't found anything.
Beta Was this translation helpful? Give feedback.
All reactions