Skip to content

Commit a7a2dbb

Browse files
gh-104010: Separate and improve docs for typing.get_origin and typing.get_args (#104013)
* 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 Co-authored-by: Jelle Zijlstra <[email protected]>
1 parent ce8d3db commit a7a2dbb

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
@@ -2876,24 +2876,37 @@ Introspection helpers
28762876
if a default value equal to ``None`` was set.
28772877
Now the annotation is returned unchanged.
28782878

2879-
.. function:: get_args(tp)
28802879
.. function:: get_origin(tp)
28812880

2882-
Provide basic introspection for generic types and special typing forms.
2883-
2884-
For a typing object of the form ``X[Y, Z, ...]`` these functions return
2885-
``X`` and ``(Y, Z, ...)``. If ``X`` is a generic alias for a builtin or
2881+
Get the unsubscripted version of a type: for a typing object of the form
2882+
``X[Y, Z, ...]`` return ``X``. If ``X`` is a generic alias for a builtin or
28862883
:mod:`collections` class, it gets normalized to the original class.
2884+
If ``X`` is an instance of :class:`ParamSpecArgs` or :class:`ParamSpecKwargs`,
2885+
return the underlying :class:`ParamSpec`.
2886+
Return ``None`` for unsupported objects.
2887+
Examples::
2888+
2889+
assert get_origin(str) is None
2890+
assert get_origin(Dict[str, int]) is dict
2891+
assert get_origin(Union[int, str]) is Union
2892+
P = ParamSpec('P')
2893+
assert get_origin(P.args) is P
2894+
assert get_origin(P.kwargs) is P
2895+
2896+
.. versionadded:: 3.8
2897+
2898+
.. function:: get_args(tp)
2899+
2900+
Get type arguments with all substitutions performed: for a typing object
2901+
of the form ``X[Y, Z, ...]`` return ``(Y, Z, ...)``.
28872902
If ``X`` is a union or :class:`Literal` contained in another
28882903
generic type, the order of ``(Y, Z, ...)`` may be different from the order
28892904
of the original arguments ``[Y, Z, ...]`` due to type caching.
2890-
For unsupported objects return ``None`` and ``()`` correspondingly.
2905+
Return ``()`` for unsupported objects.
28912906
Examples::
28922907

2893-
assert get_origin(Dict[str, int]) is dict
2908+
assert get_args(int) == ()
28942909
assert get_args(Dict[int, str]) == (int, str)
2895-
2896-
assert get_origin(Union[int, str]) is Union
28972910
assert get_args(Union[int, str]) == (int, str)
28982911

28992912
.. versionadded:: 3.8

0 commit comments

Comments
 (0)