Part 2: Data Structures, Type Hints and Pydantic
Introduction
Python's Built-in Data Structures
Lists
# Ordered, mutable, allows duplicates
hosts: list[str] = ["web-01", "web-02", "db-01"]
hosts.append("cache-01") # add to end
hosts.insert(0, "lb-01") # add at index
hosts.remove("db-01") # remove by value
popped = hosts.pop() # remove and return last item
# List comprehension โ I use this constantly in ansible-inspec
active_hosts = [h for h in hosts if h.startswith("web")]
# Slicing
first_two = hosts[:2]
reversed_hosts = hosts[::-1]Dictionaries
Sets
Tuples
Type Hints in Python 3.12
Basic annotations
Union types
Generics with built-in types (3.9+)
TypedDict โ typed dicts without a full class
TypedDict โ typed dicts without a full classtype alias (3.12)
type alias (3.12)@overload โ when a function returns different types based on input
@overload โ when a function returns different types based on inputPydantic v2
Basic model
Field validators
Nested models
JSON serialisation / deserialisation
model_config โ Pydantic v2 configuration
model_config โ Pydantic v2 configurationpydantic-settings โ environment-based config (used in ansible-inspec)
pydantic-settings โ environment-based config (used in ansible-inspec)Practical Patterns
Parsing YAML inventories
Serializing results to JSON
Summary
Concept
Key point
What's Next
PreviousPart 1: Getting Started with Python 3.12 - Setup, pyproject.toml, and Language FeaturesNextPart 3: OOP, Dataclasses and Protocols
Last updated