Type Parameter Syntax (PEP 695) & Variance
Python 3.12 replaced verbose `TypeVar` boilerplate with native type parameter syntax (`class Container[T]:`). Type parameters define generic variance, determining whether `Container[Dog]` can safely substitute for `Container[Animal]` under static type checkers (Mypy, Pyright) 📐🧬.
# Python 3.12+ Native Generic Syntax (PEP 695):
class Repository[T]:
def __init__(self, item: T):
self.item = item
def fetch(self) -> T:
return self.item
repo_int = Repository(42)
repo_str = Repository("PRODUCTION_RECORD")
# Introspect runtime type parameter definition:
type_param = Repository.__type_params__[0]
print(f"Generic Type Parameter: {type_param.__name__} (Value: {repo_str.fetch()}) 🚀")
# 87. Type Parameter Syntax (PEP 695) & Variance Before Python 3.12, defining a generic class required importing `TypeVar`, `Generic`, and manually specifying variance flags like `T = TypeVar('T', covariant=True)`. PEP 695 introduced native syntax directly into the language grammar 🛑. ```python # Legacy Boilerplate (Python <= 3.11): # from typing import TypeVar, Generic # T = TypeVar("T") # class Box(Generic[T]): ... # Modern Native Syntax (Python 3.12+ PEP 695): # class Box[T]: ... # def process[T, U](a: T, b: U) -> dict[T, U]: ... ``` ### Variance Principles 1. **Invariance (`T`)**: `Box[Dog]` is NOT a subtype of `Box[Animal]`. If you could pass `Box[Dog]` to a function expecting `Box[Animal]`, that function could put a `Cat` into your `Box[Dog]`, corrupting types upon read. 2. **Covariance (`T_co`)**: Safe for **read-only / producer** containers (e.g. `Sequence[Dog]` can be passed where `Sequence[Animal]` is expected, because you only read from it). 3. **Contravariance (`T_contra`)**: Safe for **write-only / consumer** interfaces (e.g. a `Serializer[Animal]` can be used where a `Serializer[Dog]` is needed, because any Dog is an Animal) 📐🧬. --- ### Interactive Pop-Quiz 🧠 #### What is the primary difference between Covariant (+T) and Invariant (T) generic containers in static typing? - [ ] A Covariant container allows `Container[Subclass]` where `Container[BaseClass]` is expected (read-only safe); an Invariant container requires exact type match 📐 - [ ] A Covariant container executes in C++ while an Invariant container runs in Python - [ ] A Covariant container encrypts items before storing them in memory - [ ] An Invariant container automatically converts floats to integers --- ### Practical Challenge 🎯 Using Python 3.12+ PEP 695 syntax, define a generic class `Stack[T]` with `__init__`, `push(item: T)`, and `pop() -> T`. Create a `Stack[int]`, push `10` and `20`, pop the top element, verify it equals `20`, and print the type parameter name from `Stack.__type_params__[0].__name__`. <details> <summary>Solution</summary> ```python class Stack[T]: def __init__(self): self.items = [] def push(self, item: T): self.items.append(item) def pop(self) -> T: return self.items.pop() s = Stack[int]() s.push(10) s.push(20) top = s.pop() assert top == 20 param_name = Stack.__type_params__[0].__name__ assert param_name == "T" print(param_name) ``` </details>