I'm having a hard time understanding from the documentation exactly what typing.Annotated
is good for and an even harder time finding explanations/examples outside the documentation.
Or does it "being good for something" depend entirely on what third party libraries you're using? In what (real-world) context would you use Annotated
?
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.