Repaso
EspaƱol
PythonAdvancedPY-21

What does T achieve here?

from typing import TypeVar
T = TypeVar("T")

def first(items: list[T]) -> T:
    return items[0]

Options

  1. It makes the function run faster by caching the first element
  2. It ties the return type to the element type: list[int] gives int (Correct option)
  3. It lets the function return any type, whatever the input is
  4. 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.

Key terms

Practice this question in Repaso