Reputation: 652
What is the correct way to declare the type of the following function in Python?
from typing import TypeVar, List
T = TypeVar('T') # Declare type variable
def dual_combinator(self, a: List[T], b: List[T]) -> List[T]:
return [x for x in a if x in b]
I'd like the type to indicate that the input variables a
and b
can be anything which is compatible with a list comprehension, and the in
operator, respectively, and the output should be the output of a list comprehension. I believe that a: List[T]
and b: List[T]
are probably too specific, and the return type List[T]
is probably wrong as well.
I'm very new to this particular type system. I haven't yet figured out how to find out information like this. It's probably described somewhere in the documentation, so I'd also appreciate a brief description of how to find such documentation in the future.
Upvotes: 0
Views: 2098
Reputation: 782285
The parameter you're iterating over should be Iterable
, and the parameter you're searching should be Container
.
from collections.abc import Iterable, Container
def dual_combinator(self, a: Iterable[T], b: Container[T]) -> List[T]:
return [x for x in a if x in b]
The list comprehension always returns a list, so List[T]
is the correct return type.
Upvotes: 3