Skip to content

Commit a8e902d

Browse files
miss-islingtonchgnrdvJelleZijlstra
authored
[3.11] gh-104010: Separate and improve docs for typing.get_origin and typing.get_args (GH-104013) (#104359)
* separate documentation and examples for both functions * add examples demonstrating behaviour with unsupported types * document return value of `get_origin` for `ParamSpecArgs` and `ParamSpecKwargs` instances (cherry picked from commit a7a2dbb) Co-authored-by: chgnrdv <52372310+chgnrdv@users.noreply.github.com> Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
1 parent 03abac2 commit a8e902d

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

Doc/library/typing.rst

+22-9
Original file line numberDiff line numberDiff line change
@@ -2790,24 +2790,37 @@ Introspection helpers
27902790
if a default value equal to ``None`` was set.
27912791
Now the annotation is returned unchanged.
27922792

2793-
.. function:: get_args(tp)
27942793
.. function:: get_origin(tp)
27952794

2796-
Provide basic introspection for generic types and special typing forms.
2797-
2798-
For a typing object of the form ``X[Y, Z, ...]`` these functions return
2799-
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
2795+
Get the unsubscripted version of a type: for a typing object of the form
2796+
``X[Y, Z, ...]`` return ``X``. If ``X`` is a generic alias for a builtin or
28002797
:mod:`collections` class, it gets normalized to the original class.
2798+
If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
2799+
return the underlying :class:`ParamSpec`.
2800+
Return ``None`` for unsupported objects.
2801+
Examples::
2802+
2803+
assert get_origin(str) is None
2804+
assert get_origin(Dict[str, int]) is dict
2805+
assert get_origin(Union[int, str]) is Union
2806+
P = ParamSpec('P')
2807+
assert get_origin(P.args) is P
2808+
assert get_origin(P.kwargs) is P
2809+
2810+
.. versionadded:: 3.8
2811+
2812+
.. function:: get_args(tp)
2813+
2814+
Get type arguments with all substitutions performed: for a typing object
2815+
of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
28012816
If ``X`` is a union or :class:`Literal` contained in another
28022817
generic type, the order of ``(Y, Z, ...)`` may be different from the order
28032818
of the original arguments ``[Y, Z, ...]`` due to type caching.
2804-
For unsupported objects return ``None`` and ``()`` correspondingly.
2819+
Return ``()`` for unsupported objects.
28052820
Examples::
28062821

2807-
assert get_origin(Dict[str, int]) is dict
2822+
assert get_args(int) == ()
28082823
assert get_args(Dict[int, str]) == (int, str)
2809-
2810-
assert get_origin(Union[int, str]) is Union
28112824
assert get_args(Union[int, str]) == (int, str)
28122825

28132826
.. versionadded:: 3.8

0 commit comments

Comments
 (0)