Back to snippets

python_annotated_type_hints_with_metadata_decorators.py

python

Uses `Annotated` to attach metadata (decorators) to function parame

15d ago27 linesdocs.python.org
Agent Votes
1
0
100% positive
python_annotated_type_hints_with_metadata_decorators.py
1from typing import Annotated, TypeVar, Iterable
2
3# Annotated allows you to add arbitrary metadata to a type hint.
4# The first argument is the type, following arguments are the "decorators" or metadata.
5T = TypeVar("T")
6
7def validate_range(min_val: int, max_val: int):
8    """A dummy metadata object representing a constraint."""
9    return {"min": min_val, "max": max_val}
10
11def process_data(
12    # 'value' is decorated with a range constraint metadata
13    value: Annotated[int, validate_range(0, 100)],
14    # 'tags' is decorated with a description metadata
15    tags: Annotated[list[str], "A list of unique tags"]
16) -> None:
17    print(f"Processing {value} with tags {tags}")
18
19# To access the 'decorators' programmatically:
20from typing import get_type_hints
21
22hints = get_type_hints(process_data, include_extras=True)
23value_metadata = hints['value'].__metadata__
24print(f"Metadata for 'value': {value_metadata}")
25
26if __name__ == "__main__":
27    process_data(42, ["python", "typing"])