This module introduces generic programming with type hints and reusable classes.
- Difficulty: Intermediate.
- Estimated Time: 35-50 minutes.
- Prerequisites:
01-foundations/functions,03-advanced/structs-and-classes. - Cross-Language Lens: Compare C++ templates with C# generics, Go type parameters, and Python's runtime flexibility.
python example/main.py- Generic functions through type variables.
- Generic classes with reusable element types.
- Type-independent logic with consistent interfaces.
- When type hints clarify constraints even in a dynamic language.
- Assuming type hints enforce runtime behavior by themselves.
- Replacing clear generic APIs with
Anytoo early. - Ignoring value constraints when writing supposedly reusable code.
- Compared with C++, this concept broadens from templates into each language's own reusable generic abstraction model.
- Relative to Go and C#, TypeScript generics stay expressive without runtime specialization, while Python treats the same idea more informally.
- The useful comparison is how each language generalizes logic without abandoning type clarity.
- exercises/01.py: generic swap function.
- exercises/02.py: generic average over numeric lists.
- exercises/01.py
- Input: two values of the same type.
- Output: values before and after swap.
- Edge cases: identical values; negative numbers.
- exercises/02.py
- Input: numeric sequence.
- Output: arithmetic average.
- Edge cases: empty list should return
0; mixed positive/negative values.
- I can write and call generic helper functions with type variables.
- I can create simple generic classes.
- I can identify where type hints help clarify generic code.
- I completed exercises/01.py.
- I completed exercises/02.py.