I read PEP-593 (Flexible function and variable annotations)
I decided to read PEP-593 (Flexible function and variable annotations) in the flow of a discussion, so make a note of my understanding. Leave it in.
Overview
- PEP-3107 (Function Annotations) introduced annotations into the Python grammar. At that time, the uses of annotations were type hints, DB query mapping, RPS marshalling information, and so on.
- PEP-484 (Type Hints) introduced a way to implement type hints using annotation notation. It can now be said that it is the main usage of annotations.
- Now that PEP-484 has become the de facto standard, it has become difficult to use annotations for purposes other than type hints.
- So I'll redefine the annotations so that I can write my own metadata in addition to the type hints.
approach
- Add a new
typing.Annotated
- Write ʻAnnotated [T, x, y]` when annotating a data or function with the type T and metadata x, y.
- The first element is considered a type
- Type checkers can refer to
T
, and tools and libraries that use metadata can refer to x
and y
.
- In other words, tools and libraries will ignore annotations that they don't support.
Example
Numerical (fictitious) annotations in the range 3-10 that are considered characters by ctype.
Annotated[int, ValueRange(3, 10), ctype("char")]
Impressions
- ʻAnnotated` is hard to write. I wanted to write more roughly in tuple ...
- You can get the contents of annotations even at runtime (
get_type_hints ()
), so it seems that libraries and frameworks that use this will come out.
- I hope it doesn't result in chaotic code as a result of abuse
- Although PEP-3107 (function annotation) is introduced, PEP-526 (Syntax for Variable Annotations) Is not mentioned at all. A pitiful child ...
- Of course, you can annotate variables as well as functions.
- Sphinx also has to support ...
- It seems that you can annotate the explanations of arguments and variables, but I feel that it is not popular because it is tedious to write anyway.
- I made an issue. I'm sure I will do it tomorrow ...
def hello(name: Annotated[str, Description("name")],
message: Annotated[str, Description("Message format")],
language: Annotated[str, Description("language")] = "ja"
) -> Annotated[None, Description("None")]:
...