You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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 commentedon Sep 16, 2024
You should not use this directly, but use
typing.get_origininstead. However, we could document this explicitly.pythongh-124120: Document use of `get_origin` to access `Annotated` o…
JelleZijlstra commentedon Sep 16, 2024
Actually, looking at the code some more this is not true. For some reason there is a special case where
.__origin__andget_origin()(as well as__args__andget_args()) are not aligned for Annotated.This aligns with the documentation, which promises that for
X[Y, ...],get_origin()will returnX. 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 forAnnotatedas @ncoghlan originally suggested.sobolevn commentedon 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,
Annotatedis the unsubscripted version of a type. And anyTwrapped 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 commentedon Sep 26, 2024
Backports have been merged, so marking this as complete. Thanks, folks!