How to infer the type of the first element in an iterable in MyPy/Pyright?
Is there any way to annotate the code below to a bit more narrow scoped?
Meaning that I want the type checker to assume that the function below returns an object of the type that is contained in the iterable or list.
from typing import Iterable, List, TypeVar
T = TypeVar('T')
def get_first(iterable: Iterable[T] | List[T]) -> T | None:
for item in iterable:
return item
return None
For example:
class Bob:
pass
ll = [Bob(), Bob()] # Create a list that contains objects of type Bob
first_bob = get_first(ll) # <--- Type checker should infer that the type of first_bob is Bob
I am looking for a solution that works specifically in MyPy/Pyright.