Interview Prep/Python for DevOps/Language essentials & functions

What are generics in type hints (`TypeVar`, `list[T]`)?

AdvancedConceptLanguage essentials & functions
Answer

Generics let a function or class be typed in terms of its inputs:

from typing import TypeVar
T = TypeVar("T")
def chunked(items: list[T], size: int) -> Iterator[list[T]]:
    for i in range(0, len(items), size):
        yield items[i:i + size]

chunked(instance_ids, 50) is inferred as Iterator[list[str]]. Python 3.12 adds the shorter syntax def chunked[T](items: list[T], size: int) -> Iterator[list[T]]:. Batching IDs is common because many AWS APIs cap a call (for example 1000 IDs for describe_instances filters, 200 for some tagging calls).

All Python for DevOps questions Roadmap: Python for automation

More on Language essentials & functions