The typing module docs cover using Annotated.__metadata__ to retrieve the annotations, but they do not currently cover the use of Annotated.__origin__ to retrieve the underlying type hint that is being annotated.
Actually, looking at the code some more this is not true. For some reason there is a special case where .__origin__ and get_origin() (as well as __args__ and get_args()) are not aligned for Annotated.
This aligns with the documentation, which promises that for X[Y, ...], get_origin() will return X. However, it is confusing that it does not also align with the __origin_ attribute.
Since __origin__ is otherwise undocumented, it's probably best to document it specifically for Annotated as @ncoghlan originally suggested.
Activity
JelleZijlstra commented on Sep 16, 2024
You should not use this directly, but use typing.get_origin instead. However, we could document this explicitly.
pythongh-124120: Document use of `get_origin` to access `Annotated` o…
JelleZijlstra commented on Sep 16, 2024
Actually, looking at the code some more this is not true. For some reason there is a special case where .__origin__ and get_origin() (as well as __args__ and get_args()) are not aligned for Annotated.
This aligns with the documentation, which promises that for X[Y, ...], get_origin() will return X. However, it is confusing that it does not also align with the __origin_ attribute.
Since __origin__ is otherwise undocumented, it's probably best to document it specifically for Annotated as @ncoghlan originally suggested.
sobolevn commented on Sep 16, 2024
I made this mistake in the first version of #124125
But, then I realized the same thing as in #124120 (comment)
Why? Because of these two lines:
cpython/Lib/typing.py
Lines 2507 to 2508 in 9aa1f60
I think that it makes sense:
So, Annotated is the unsubscripted version of a type. And any T wrapped by it is just the first type arg.
gh-124120: Document `Annotated.__origin__` (#124125)
pythongh-124120: Document `Annotated.__origin__` (pythonGH-124125)
pythongh-124120: Document `Annotated.__origin__` (pythonGH-124125)
[3.12] gh-124120: Document `Annotated.__origin__` (GH-124125) (#124417)
[3.13] gh-124120: Document `Annotated.__origin__` (GH-124125) (#124416)
ncoghlan commented on Sep 26, 2024
Backports have been merged, so marking this as complete. Thanks, folks!