Back
+20 XP
Concept

Static Type Checking with mypy & Variance

Type annotations communicate intent; static type checkers (`mypy`, `pyright`) verify type safety. Generics rely on variance: covariance (`covariant=True`) permits reading child subtypes safely in read-only containers 📐.

python
from typing import TypeVar, Generic

# Covariant type parameter (producer-only):
T_co = TypeVar("T_co", covariant=True)

class ImmutableBox(Generic[T_co]):
    def __init__(self, item: T_co):
        self._item = item

    def get(self) -> T_co:
        return self._item

box = ImmutableBox(42)
print(f"Box value: {box.get()} 📐")

# 102. Static Type Checking with mypy & Variance Type annotations communicate intent; static type checkers (`mypy`, `pyright`) verify type safety. Generics rely on variance: covariance (`covariant=True`) permits reading child subtypes safely in read-only containers 📐. ```python from typing import TypeVar, Generic # Covariant type parameter (producer-only): T_co = TypeVar("T_co", covariant=True) class ImmutableBox(Generic[T_co]): def __init__(self, item: T_co): self._item = item def get(self) -> T_co: return self._item box = ImmutableBox(42) print(f"Box value: {box.get()} 📐") ``` Python 3.12 simplified generic syntax with PEP 695 type parameter syntax: `class Box[T]: ...` replaces verbose `TypeVar` declarations with clean, first-class generic syntax 🚀! --- ### Question Why must a mutable collection like `list[T]` be strictly invariant in static type theory? 🧠 - [ ] a. If `list[Dog]` were accepted where `list[Animal]` is expected, code could insert a `Cat`, violating type safety 📐 - [ ] b. Python's memory manager cannot dynamically allocate memory for covariant lists - [ ] c. Invariant types execute without invoking the garbage collector - [ ] d. Static type checkers cannot parse lists containing more than one element --- ### Challenge Define `T_co = TypeVar('T_co', covariant=True)`. Define `Producer(Generic[T_co])` with `get(self) -> T_co`. Instantiate with `100` and print `p.get()`. 🎯 <details> <summary>Solution</summary> ```python from typing import TypeVar, Generic T_co = TypeVar('T_co', covariant=True) class Producer(Generic[T_co]): def __init__(self, val: T_co): self.val = val def get(self) -> T_co: return self.val p = Producer(100) print(p.get()) ``` </details>

Checkpoint

Why must a mutable collection like `list[T]` be strictly invariant in static type theory? 🧠

Practice

Define `T_co = TypeVar('T_co', covariant=True)`. Define `Producer(Generic[T_co])` with `get(self) -> T_co`. Instantiate with `100` and print `p.get()`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks