diff options
author | Ivan Levkivskyi <levkivskyi@gmail.com> | 2019-05-30 23:10:07 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-30 23:10:07 (GMT) |
commit | 4c23aff065fb28aba789a211937a2af974842110 (patch) | |
tree | f6f2757eb59d315e2835f7dcf8b2f1b7f18506ea /Doc/library/typing.rst | |
parent | 2a58b0636d1f620f8a85a2e4c030cc10551936a5 (diff) | |
download | cpython-4c23aff065fb28aba789a211937a2af974842110.zip cpython-4c23aff065fb28aba789a211937a2af974842110.tar.gz cpython-4c23aff065fb28aba789a211937a2af974842110.tar.bz2 |
bpo-29262: Add get_origin() and get_args() introspection helpers to typing (GH-13685)
This is an old feature request that appears from time to time. After a year of experimenting with various introspection capabilities in `typing_inspect` on PyPI, I propose to add these two most commonly used functions: `get_origin()` and `get_args()`. These are essentially thin public wrappers around private APIs: `__origin__` and `__args__`.
As discussed in the issue and on the typing tracker, exposing some public helpers instead of `__origin__` and `__args__` directly will give us more flexibility if we will decide to update the internal representation, while still maintaining backwards compatibility.
The implementation is very simple an is essentially a copy from `typing_inspect` with one exception: `ClassVar` was special-cased in `typing_inspect`, but I think this special-casing doesn't really help and only makes things more complicated.
Diffstat (limited to 'Doc/library/typing.rst')
-rw-r--r-- | Doc/library/typing.rst | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst index 709580a..2575a99 100644 --- a/Doc/library/typing.rst +++ b/Doc/library/typing.rst @@ -1021,6 +1021,25 @@ The module defines the following classes, functions and decorators: a dictionary constructed by merging all the ``__annotations__`` along ``C.__mro__`` in reverse order. +.. function:: get_origin(typ) +.. function:: get_args(typ) + + 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. + For unsupported objects return ``None`` and ``()`` correspondingly. + Examples:: + + assert get_origin(Dict[str, int]) is dict + assert get_args(Dict[int, str]) == (int, str) + + assert get_origin(Union[int, str]) is Union + assert get_args(Union[int, str]) == (int, str) + + .. versionadded:: 3.8 + .. decorator:: overload The ``@overload`` decorator allows describing functions and methods |