How to use typing.Annotated
Apr 17
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
Jun 4
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.
Apr 17
typing.Annotation allows you to do that but also annotate it with the type.May 16
pydantic that uses Annotated to impose additional validators.