Generic classes declare parameters so type checkers can track the types they contain.
What It Does and Why It Matters
Generic classes declare parameters so type checkers can track the types they contain. Generic aliases such as type Pair[ItemType] = tuple[ItemType, ItemType] share the same parameter for both elements.
Annotations guide static tools; by default they do not validate external input or change the return value at runtime.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
class StorageBox[ItemType]:
def __init__(self, item: ItemType) -> None:
self.item = item
type Pair[ItemType] = tuple[ItemType, ItemType]
selected_box = StorageBox('active')
print(selected_box.item)
How the Code Works
- The definition of StorageBox creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The name selected_box receives the value of StorageBox('active'). Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
active
For the demonstrated inputs, Python displays 'active'. This result follows from the operation described above; change one input at a time to understand which rule matters.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Build a generic Result container that stores one typed value.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Using different unrelated types in a generic pair where both values should share one type parameter.
- Checking only the easiest input and missing a relevant error or boundary case.
Key Takeaways
- Generic classes declare parameters so type checkers can track the types they contain.
- Build a generic Result container that stores one typed value.
- Annotations guide static tools; by default they do not validate external input or change the return value at runtime.