3.10. Typing Annotated¶
Since Python 3.9 PEP 593 -- Flexible function and variable annotations
https://docs.python.org/3/library/typing.html#typing.Annotated
Note
ValueRange
, ctype
, MatchesRegex
, MaxLen
does not exist in Python. It is used only as an example
both here and in PEP 593.
3.10.1. SetUp¶
>>> from typing import Annotated
3.10.2. Numeric¶
>>> digit = Annotated[int, ValueRange(0,9)]
>>> int8 = Annotated[int, ValueRange(-128, 127), ctype('int8')]
>>> uint8 = Annotated[int, ValueRange(0, 255), ctype('uint8')]
>>> kelvin = Annotated[float, ValueRange(0.0, float('inf'))]
>>> vector = Annotated[list[int], MaxLen(3)]
3.10.3. Character¶
>>> firstname = Annotated[str, MaxLen(10)]
>>> lastname = Annotated[str, MinLen(2), MaxLen(10)]
3.10.4. Patterns¶
>>> jira_issuekey = Annotated[str, MatchesRegex('^[A-Z]{2,10}-[0-9]{1,6}$')]
>>> email = Annotated[str, MatchesRegex('^[a-z]{1,20}@nasa.gov$')]
3.10.5. Use Case - 0x01¶
>>>
... EmailAddress = Annotated[str, MatchesRegex('^[a-z]{1,20}@nasa.gov$')]
...
... def send_email(recipient: EmailAddress):
... ...
...
...
... send_email('mwatney@nasa.gov') # ok
... send_email('avogel@esa.int') # error
3.10.6. Use Case - 0x02¶
>>>
... IssueKey = Annotated[str, MatchesRegex('^[A-Z]{2,10}-[0-9]{1,6}$')]
...
... def comment(issuekey: IssueKey, text: str):
... ...
...
...
... comment('MYPROJ-1337', 'Issue was resolved successfully.')