Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 15 / Topic 2 of 6

Generics you write

Part 11 used built-in generics like list[str] and ended with "generics you write yourself... are coming in Stage 3". A generic function or class works with many types, while a type checker still tracks which type is in play for one particular call. Since Python 3.12 (PEP 695) you write this with square brackets right on the def or class line, no import needed for the basic case. Think of a courier box that is the same box whatever you put inside, but a label records what is inside this particular box.

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

print(first(["Asha", "Ravi"]))   # Asha   (T is str here)
print(first([1760.0, 540.0]))    # 1760.0 (T is float here)

T is a type parameter: a placeholder mypy fills in with the real type for each call. Without it, def first(items: list) -> object would lose the connection between what goes in and what comes out; -> object makes every caller re-check the type.

Bounding a type parameter

T: (int, float) restricts T to the types listed, so the function body can use > safely.

def largest[T: (int, float)](items: list[T]) -> T:
    biggest = items[0]
    for item in items[1:]:
        if item > biggest:
            biggest = item
    return biggest

print(largest([3, 1, 7, 2]))     # 7

largest(["a", "b"]) would be flagged by mypy: str is not in the bound.

A generic class: class Box[T]

class Box[T]:
    def __init__(self, item: T) -> None:
        self._item = item
    def get(self) -> T:
        return self._item
    def set(self, item: T) -> None:
        self._item = item

price_box: Box[float] = Box(1999.0)
price_box.set(1499.0)
print(price_box.get())           # 1499.0
# price_box.set("free") # mypy error: expected float, got str

Box[float] and Box[str] are the same class, but mypy checks each one as if it had been written specially for that type.

๐Ÿ” Going deeper: before 3.12, the same thing needed TypeVar("T") plus Generic[T], which you will still see in older code and some libraries. The square-bracket syntax is the modern way; both compile to the same idea underneath.

Full program: examples/02_generics_pep695.py.

Exercise 2: A generic last() and a generic Pair

Scenario: You keep writing near-identical "give me the last item" helpers for different list types, and a small two-value container that needs to remember what type it holds. What to do: Inside main():

  1. Write def last[T](items: list[T]) -> T: returning items[-1].
  2. Write class Pair[T]: with first/second set in __init__, a swap() method that swaps them in place, and __repr__ returning f"Pair({self.first!r}, {self.second!r})".
  3. Print last(["Asha", "Ravi", "Meera"]) and last([1760, 540, 2999]).
  4. Make cities: Pair[str] = Pair("Pune", "Mumbai"), print it, call cities.swap(), print it again.
  5. Make scores: Pair[int] = Pair(88, 95) and print it.

Sample output:

last(names)  : Meera
last(amounts): 2999
before swap  : Pair('Pune', 'Mumbai')
after swap   : Pair('Mumbai', 'Pune')
scores       : Pair(88, 95)

๐Ÿ’ก Hint: self.first, self.second = self.second, self.first swaps both in one line (Part 2's tuple assignment).


Show the solution to Exercise 2
"""Exercise 2: A generic last() function and a generic Pair class.

Shows: PEP 695 generic syntax, def f[T]() and class C[T].

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""


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


class Pair[T]:
    def __init__(self, first: T, second: T) -> None:
        self.first = first
        self.second = second

    def swap(self) -> None:
        self.first, self.second = self.second, self.first

    def __repr__(self) -> str:
        return f"Pair({self.first!r}, {self.second!r})"


def main() -> None:
    names = ["Asha", "Ravi", "Meera"]
    amounts = [1760, 540, 2999]

    print("last(names)  :", last(names))
    print("last(amounts):", last(amounts))

    cities: Pair[str] = Pair("Pune", "Mumbai")
    print("before swap  :", cities)
    cities.swap()
    print("after swap   :", cities)

    scores: Pair[int] = Pair(88, 95)
    print("scores       :", scores)


if __name__ == "__main__":
    main()

Search the guide