TypeVar
- Python course
- Advanced
- Lesson 11/83
- 5 min
Learn generic functions with TypeVar.
TypeVar
Sometimes a function must return the same type it received. TypeVar declares such a type variable.
from typing import TypeVar, List
T = TypeVar("T")
def first(items: List[T]) -> T:
return items[0]Here T stands for any type. Calling first([1, 2, 3]) returns int; calling first(["a", "b"]) returns str. The type is preserved with the argument.
You can bound a TypeVar: TypeVar("T", bound=int) accepts only int subtypes.
Safe first item with TypeVar
Without TypeVar, first looks like it returns Any; the type is lost. With TypeVar, first([1, 2, 3]) clearly returns int.
This lets the IDE offer correct completion. When you write first(["a", "b"]).upper(), the IDE suggests .upper() because it knows the return is str.
Multiple TypeVars are allowed: K = TypeVar("K"), V = TypeVar("V"). This is useful for generic dict functions.
Practice first function with TypeVar
Define T = TypeVar("T"). Write first(items: List[T]) -> T; the body contains return items[0]. Import TypeVar and List from typing. Call print(first([1, 2, 3])).
Starter code
# import TypeVar and List from typing
# declare a type variable named T
# first(items: List[T]) -> T: return the first item
# print the result of first([1, 2, 3])Sample solution
from typing import TypeVar, List
T = TypeVar("T")
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3]))Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Define a TypeVar
from typing import TypeVar
T = ____("T")
def first(items):
return items[0]
from typing import TypeVar
T = TypeVar("T")
def first(items):
return items[0]
Explanation: T = TypeVar("T") declares a type variable; it stands for any type.
2 Match the TypeVar concepts
| Term | Meaning |
|---|---|
T = TypeVar("T") |
Type variable declaration |
List[T] |
List of T |
-> T |
Returns T |
bound=int |
Bound: int subtypes |
3 What is the main benefit of TypeVar?
- Faster runtime
- Lower memory use
- Type preservation and correct IDE suggestions Correct answer
- Automatic error fixing
Explanation: TypeVar preserves type info; mypy and the IDE become more accurate.