How to use typing.Annotated
24 Nov 2023, 19:10 UTC
I'm having a hard time understanding what typing.Annotated is good for from the documentation and an even harder time finding explanations/examples outside the documentation. In what context would you use Annotated? Does it depend on third-party libraries?
1 answer
Accepted answer · original discussion
29 Nov 2023, 14:22 UTC
Annotated in python allows developers to declare the type of a reference and provide additional information related to it.
name: Annotated[str, "first letter is capital"]
This tells that name is of type str and that name[0] is a capital letter.
On its own Annotated does not do anything other than assigning extra information (metadata) to a reference. It is up to another code, which can be a library, framework or your own code, to interpret the metadata and make use of it.
For example, FastAPI uses Annotated for data validation:
def read_items(q: Annotated[str, Query(max_length=50)])
Here the parameter q is of type str with a maximum length of 50. This information was communicated to FastAPI (or any other underlying library) using the Annotated keyword.
3 question comments
Use comments to ask for clarification. Post a solution as an answer.
25 Nov 2023, 23:58 UTC
typing.Annotation allows you to do that but also annotate it with the type.27 Nov 2023, 04:46 UTC
pydantic that uses Annotated to impose additional validators.