Type Hints & Annotations
Generics
TypeVar and Generic — building reusable, type-safe containers and functions that work with any type while maintaining static checking.
Interview: Advanced typing — shows ability to design reusable, type-safe abstractions.
Generics allow you to write classes and functions that work with any type while maintaining type safety. Using TypeVar and Generic, you can create reusable containers (Stack, Queue, Cache) where the element type is tracked by the type checker.
TypeVar
T = TypeVar('T')— unconstrained, accepts any typeT = TypeVar('T', int, str)— constrained to int or str onlyT = TypeVar('T', bound=Number)— must be a subclass of Number- Same TypeVar used in params and return type links them together
Generic Classes
- Inherit from
Generic[T]to make a class parameterized by type Stack[int]creates a stack that only accepts ints- Python 3.12+ syntax:
class Stack[T]:(no TypeVar needed)
Interview Insight
Be able to implement a generic Stack or Cache class. Know how TypeVar links input and output types — if input is T, output is also T, not Any.
Use Cases
Reusable containers — Stack, Queue, Cache, LinkedList with type safety
Utility functions — first, last, identity that work with any type
Repository pattern — generic data access layer
Middleware — generic request/response handlers
Builder patterns — type-safe fluent API builders
Common Mistakes
Using Any instead of TypeVar — loses type safety benefits
Not linking TypeVar in params and return type — checker can't infer output
Forgetting to inherit from Generic[T] in generic classes
Using mutable default arguments in generic class __init__
Not using bound or constraints when the type should be restricted