Code

Generic Cargo

Some functions work with any type, but the types are linked: "give me a list of X and I'll give you back an X". A type variable expresses that link. Modern Python (3.12+) has a neat syntax. Put the type parameter in square brackets after the name:

def last[T](items: list[T]) -> T:
    return items[-1]

last([1, 2, 3])        # checker knows: int
last(["oil", "wick"])  # checker knows: str

Classes can be generic too:

class Crate[T]:
    def __init__(self, item: T) -> None:
        self.item = item

c: Crate[str] = Crate("map")

Older code (and many libraries) spell it with TypeVar:

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

def last(items: list[T]) -> T: ...

Both mean the same thing. Without generics you'd write -> object and lose all the information about what comes back.

Assignment

Use the new bracket syntax for both:

  1. first_or[T](items: list[T], default: T) -> T: return the first item, or default if the list is empty.
  2. class Stash[T] with put(self, item: T) -> None, take(self) -> T (removes and returns the most recently put item) and __len__. Store items in a list self.items.