Idea: Simpler and More Expressive Type Annotations

Being able to evaluate annotations in a typing-specific context could iron out some of the subtle differences that already exist depending on syntax.

For example, the union syntax and typing.Union don’t produce the same objects at runtime when one of the items in the union is unknown and so annotationlib doesn’t assume the syntax implies a union. If these were evaluated with that assumption then it would be possible to get the actual union in both cases.

>>> from annotationlib import get_annotations, Format
>>> from typing import Union
>>> from pprint import pp
>>> 
>>> class Example:
...     syntax: str | unknown
...     subscript: Union[str, unknown]
...     
>>> pp(get_annotations(Example, format=Format.FORWARDREF))
{'syntax': ForwardRef('__annotationlib_name_1__ | unknown', is_class=True, owner=<class '__main__.Example'>),
 'subscript': str | ForwardRef('unknown', is_class=True, owner=<class '__main__.Example'>)}

If extra formats were added to annotate I would however like if they could also solve the issue I brought up before with regards to the need to create new __annotate__ functions[1].


  1. like the one in dataclasses where I accidentally broke certain dataclasses in 3.14.1 :frowning: ↩︎

1 Like