Skip to content

Document Annotated.__origin__ #124120

Closed
Closed

Description

@ncoghlan

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.

>>> from typing import Annotated
>>> Annotated[int, ""].__metadata__
('',)
>>> Annotated[int, ""].__origin__
<class 'int'>

Linked PRs

Activity

  1. JelleZijlstra commented on Sep 16, 2024

    @JelleZijlstra
    Member

    You should not use this directly, but use typing.get_origin instead. However, we could document this explicitly.

  2. added a commit that references this issue on Sep 16, 2024
  3. JelleZijlstra commented on Sep 16, 2024

    @JelleZijlstra
    Member

    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.

    >>> a = Annotated[int, "x"]
    >>> a.__origin__
    <class 'int'>
    >>> a.__args__
    (<class 'int'>,)
    >>> typing.get_origin(a)
    <class 'typing.Annotated'>
    >>> typing.get_args(a)
    (<class 'int'>, 'x')
    

    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.

  4. sobolevn commented on Sep 16, 2024

    @sobolevn
    Member

    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

    if isinstance(tp, _AnnotatedAlias):
    return Annotated

    I think that it makes sense:

    Get the unsubscripted version of a type.

    So, Annotated is the unsubscripted version of a type. And any T wrapped by it is just the first type arg.

  5. added a commit that references this issue on Sep 24, 2024
  6. added 2 commits that reference this issue on Sep 24, 2024
  7. added a commit that references this issue on Sep 24, 2024
  8. added a commit that references this issue on Sep 24, 2024
  9. ncoghlan commented on Sep 26, 2024

    @ncoghlan
    ContributorAuthor

    Backports have been merged, so marking this as complete. Thanks, folks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions