typestar

TypeVar and Generic in Python

A type parameter lets one class or function keep its caller's type.

from typing import Generic, TypeVar

T = TypeVar("T")


def first(items: list[T]) -> T | None:
    return items[0] if items else None


class Stack(Generic[T]):
    def __init__(self) -> None:
        self._items: list[T] = []

    def push(self, item: T) -> None:
        self._items.append(item)

    def pop(self) -> T:
        return self._items.pop()


numbers: Stack[int] = Stack()
numbers.push(3)
print(first([1, 2, 3]), first([]), numbers.pop())

How it works

  1. A TypeVar links the argument type to the return type.
  2. Generic[T] makes a class parameterized.
  3. Modern syntax writes the parameter in brackets after the name.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
413
Tokens
147
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 1 of 4 in Typing in depth, step 41 of 53 in Pythonic Python.

← Previous Next →