Trait Bounds
Hard
+4 pts
🎯 In Python, function signatures don't constrain what types are allowed:
def largest(items): return max(items) # works if items support comparison, crashes if not largest([3, 1, 4]) # 4 largest(["a", "c", "b"]) # "c" largest([{}, {}]) # TypeError at runtime
You find out about type mismatches when the code runs. Type hints help, but they're advisory:
from typing import TypeVar T = TypeVar("T", bound=Comparable) def largest(items: list[T]) -> T: return max(items)
Rust's trait bounds serve the …
Login to see the full exercise.
Topics