python 3.12 type hints generics TypeVar ParamSpec 2024 Challenge
Read the problem description and solve the challenge in the workspace.
Here is a practical Coding Challenge based on the concepts taught in the Python Type Hints (3.12+) tutorial.
Coding Challenge: The Type-Safe Shipping Factory Pipeline
Problem Description Imagine you're basically managing a massive shipping factory that acts as the backend for the blazing-fast data aggregation dashboard; you have high-speed conveyor belts moving various batches of data—sometimes you're basically processing lists of integers for heavy CPU workloads, and other times you are processing dictionaries containing external API user statistics.
If a worker expecting a box of "soft pillows" (dictionaries) accidentally receives "heavy bowling balls" (integers), system will crash! Python is dynamically typed, so to protect your factory you must place strict labels on your conveyor belts, while
your challenge is to build the highly reliable generic batch processing function. You really have to completely abandon the old clunky TypeVar imports and implement the clean, cutting-edge Python 3.12+ generic syntax towards ensure the static analyzer instantly knows exactly what type of data is flowing through the system.
Difficulty Level: Advanced
Input & Output Specifications
* Input:
* batch: THE list of items with any generic type (e.g., a list of integers, or a list of dictionaries).
* Output:
* Returns a List containing the processed items.
* The type hint must strictly guarantee that the returned list contains the exact same data type as the input list, completely preserving the generic type structure.
Starter Code Boilerplate
# Ensure you are using Python 3.12+
# TODO: Define your generic batch processor using the new Python 3.12 syntax
# Replace the old TypeVar boilerplate with the modern generic type parameter.
def process_batch(batch: ...) -> ...:
"""
Safely processes a batch of items, strictly maintaining their original data type.
"""
processed_items = []
for item in batch:
# Simulated processing logic
processed_items.append(item)
return processed_items
# Simulated Factory Data Streams
if __name__ == '__main__':
# Stream 1: Dictionaries of strings to integers
api_responses: list[dict[str, int]] = [{"users": 150}, {"users": 42}]
# Stream 2: Integers for CPU processing
cpu_workloads: list[int] =
# Test the generic function safely
# safe_api_data = process_batch(api_responses)
# safe_cpu_data = process_batch(cpu_workloads)
Hints
* The Python 3.12 Generics Syntax: You no longer need to use from typing import TypeVar and rigidly assign it to a variable. Instead, cleanly define your type parameter by placing square brackets [T] directly next to your function name.
* Typing Containers: Remember that types parameterized by other types are called generic types. If your function accepts the list of generic items, argument should be typed as list[T].
* Enforcing the Output: To build a bulletproof system, your return type hint must also be list[T]. This tells a static analyzer that whatever type goes into the factory is exactly the type that comes out.
Test Cases
- Test Case 1 (API Data Dictionaries):
- Input:
[{"status": 200, "users": 150}, {"status": 200, "users": 42}] - Expected Output:
[{"status": 200, "users": 150}, {"status": 200, "users": 42}] -
Static Analysis Expectation: A static analyzer should confirm the output type is safely recognized as
list[dict[str, int]]. -
Test Case 2 (CPU Workload Integers):
- Input: ``
- Expected Output: ``
-
Static Analysis Expectation: A static analyzer should confirm the output type is safely recognized as
list[int]. -
Test Case 3 (Static Analyzer Failure on Type Mismatch):
- Scenario: If a developer tries to pass
["string_1", "string_2"]into the function but incorrectly assigns an output to a variable explicitly typed aslist[int]. - Expected Behavior: The code will run, but the static analyzer will explicitly flag severe factory mismatch, protecting your application from crashing in production!