Back
+15 XP
Concept

Generics & TypeVar: Reusable Type Safety

`TypeVar` defines generic type parameters. It preserves the exact input type through to the return type, allowing static linters to enforce consistency across diverse types 🧬.

python
from typing import TypeVar, List

T = TypeVar('T')

def get_first(items: List[T]) -> T:
    return items[0]

num = get_first([10, 20, 30])      # Inferred as int 🧬
word = get_first(["alpha", "beta"]) # Inferred as str 🚀
print(f"{num} ({type(num).__name__}), {word} ({type(word).__name__})")

# 91. Generics & TypeVar: Reusable Type Safety `TypeVar` defines generic type parameters. It preserves the exact input type through to the return type, allowing static linters to enforce consistency across diverse types 🧬. ```python from typing import TypeVar, List T = TypeVar('T') def get_first(items: List[T]) -> T: return items[0] num = get_first([10, 20, 30]) # Inferred as int 🧬 word = get_first(["alpha", "beta"]) # Inferred as str 🚀 print(f"{num} ({type(num).__name__}), {word} ({type(word).__name__})") ``` Without `TypeVar`, annotating as `Any` loses all type safety; your IDE wouldn't know whether `get_first(['a'])` returns a string or an integer! 🧬 --- ### Question Why is `TypeVar('T')` superior to using `Any` for reusable functions? 🧠 - [ ] a. It binds the return type to match the exact input type passed at call-site 🧬 - [ ] b. It automatically compiles the Python code into C++ templates - [ ] c. It restricts the function to integers only - [ ] d. It speeds up runtime execution by bypassing CPython bytecode --- ### Challenge Import `TypeVar`, `List` from `typing`. Define `T = TypeVar('T')` and `def last_item(items: List[T]) -> T: return items[-1]`. Print `last_item([1, 2, 3])`. 🎯 <details> <summary>Solution</summary> ```python from typing import TypeVar, List T = TypeVar("T") def last_item(items: List[T]) -> T: return items[-1] print(last_item([1, 2, 3])) ``` </details>

Checkpoint

Why is `TypeVar('T')` superior to using `Any` for reusable functions? 🧠

Practice

Import `TypeVar`, `List` from `typing`. Define `T = TypeVar('T')` and `def last_item(items: List[T]) -> T: return items[-1]`. Print `last_item([1, 2, 3])`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks