Login Sign Up
Python Type Hints (3.12+)
Courses / python Complete Course / Python Type Hints (3.12+)
Chapter 39 🟡 Intermediate

Python Type Hints (3.12+)

Apply your skills with a real-world coding challenge. Try to solve it yourself first!

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

  1. Test Case 1 (API Data Dictionaries):
  2. Input: [{"status": 200, "users": 150}, {"status": 200, "users": 42}]
  3. Expected Output: [{"status": 200, "users": 150}, {"status": 200, "users": 42}]
  4. Static Analysis Expectation: A static analyzer should confirm the output type is safely recognized as list[dict[str, int]].

  5. Test Case 2 (CPU Workload Integers):

  6. Input: ``
  7. Expected Output: ``
  8. Static Analysis Expectation: A static analyzer should confirm the output type is safely recognized as list[int].

  9. Test Case 3 (Static Analyzer Failure on Type Mismatch):

  10. Scenario: If a developer tries to pass ["string_1", "string_2"] into the function but incorrectly assigns an output to a variable explicitly typed as list[int].
  11. Expected Behavior: The code will run, but the static analyzer will explicitly flag severe factory mismatch, protecting your application from crashing in production!

Loading sandbox workspace environment...

Verify Your Solution

Write your solution in the compiler, run it to verify output, then click below to verify.

Learn Together
Session active! Discuss with other learners.
No notes yet. Select text in the concept body to add a note.