
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:
first_or[T](items: list[T], default: T) -> T: return the first item, ordefaultif the list is empty.class Stash[T]withput(self, item: T) -> None,take(self) -> T(removes and returns the most recently put item) and__len__. Store items in a listself.items.
Use the new bracket syntax for both:
first_or[T](items: list[T], default: T) -> T: return the first item, ordefaultif the list is empty.class Stash[T]withput(self, item: T) -> None,take(self) -> T(removes and returns the most recently put item) and__len__. Store items in a listself.items.
main.py Python sleeping
Press Run to try your code, then Check to test it.