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).
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat is the difference between mutable and immutable types? Give examples.BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?Beginner