Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-104010: Separate and improve docs for typing.get_origin and typing.get_args #104013

Merged
31 changes: 22 additions & 9 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2882,24 +2882,37 @@ Introspection helpers
Now the annotation is returned unchanged.

.. function:: get_args(tp)
.. function:: get_origin(tp)

Provide basic introspection for generic types and special typing forms.

For a typing object of the form ``X[Y, Z, ...]`` these functions return
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
:mod:`collections` class, it gets normalized to the original class.
Get type arguments with all substitutions performed: for a typing object
of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
If ``X`` is a union or :class:`Literal` contained in another
generic type, the order of ``(Y, Z, ...)`` may be different from the order
of the original arguments ``[Y, Z, ...]`` due to type caching.
For unsupported objects return ``None`` and ``()`` correspondingly.
Return ``()`` for unsupported objects.
Examples::

assert get_origin(Dict[str, int]) is dict
assert get_args(int) == ()
assert get_args(Dict[int, str]) == (int, str)
assert get_args(Union[int, str]) == (int, str)

.. versionadded:: 3.8

.. function:: get_origin(tp)

Get the unsubscripted version of a type: for a typing object of the form
``X[Y, Z, ...]`` return ``X``. If ``X`` is a generic alias for a builtin or
:mod:`collections` class, it gets normalized to the original class.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add that for ParamSpecArgs and Kwargs, it returns the underlying ParamSpec.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

If ``X`` is an instance of :class:``ParamSpecArgs`` or :class:``ParamSpecKwargs``,
return the underlying :class:``ParamSpec``.
JelleZijlstra marked this conversation as resolved.
Show resolved Hide resolved
Return ``None`` for unsupported types.
Examples::

assert get_origin(str) is None
assert get_origin(Dict[str, int]) is dict
assert get_origin(Union[int, str]) is Union
assert get_args(Union[int, str]) == (int, str)
P = ParamSpec('P')
assert get_origin(P.args) is P
assert get_origin(P.kwargs) is P

.. versionadded:: 3.8

Expand Down