What does T achieve here?
from typing import TypeVar
T = TypeVar("T")
def first(items: list[T]) -> T:
return items[0]Options
- It makes the function run faster by caching the first element
- It ties the return type to the element type:
list[int]givesint(Correct option) - It lets the function return any type, whatever the input is
- It enforces the types at runtime and raises an error on mismatch
Answer
It ties the return type to the element type: list[int] returns int
Why
A TypeVar is a placeholder for a type, like a variable but for types.
list[T] -> T says: whatever type is inside the list, the function returns that same type. A type checker then knows first([1, 2]) is an int and first(["a"]) is a str.
Python itself does not check this when running; tools like mypy or pyright do.
Remember
TypeVar links the input type to the output type.