Skip to content

[3.9] bpo-44392: Add Py_GenericAlias to C API docs (GH-26724) #26757

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

Merged
merged 2 commits into from
Jun 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Doc/c-api/concrete.rst
Original file line number Diff line number Diff line change
Expand Up @@ -115,3 +115,4 @@ Other Objects
coro.rst
contextvars.rst
datetime.rst
typehints.rst
46 changes: 46 additions & 0 deletions Doc/c-api/typehints.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
.. highlight:: c

.. _typehintobjects:

Objects for Type Hinting
------------------------

Various built-in types for type hinting are provided.
Only :ref:`GenericAlias <types-genericalias>` is exposed to C.

.. c:function:: PyObject* Py_GenericAlias(PyObject *origin, PyObject *args)

Create a :ref:`GenericAlias <types-genericalias>` object.
Equivalent to calling the Python class
:class:`types.GenericAlias`. The *origin* and *args* arguments set the
``GenericAlias``\ 's ``__origin__`` and ``__args__`` attributes respectively.
*origin* should be a :c:type:`PyTypeObject*`, and *args* can be a
:c:type:`PyTupleObject*` or any ``PyObject*``. If *args* passed is
not a tuple, a 1-tuple is automatically constructed and ``__args__`` is set
to ``(args,)``.
Minimal checking is done for the arguments, so the function will succeed even
if *origin* is not a type.
The ``GenericAlias``\ 's ``__parameters__`` attribute is constructed lazily
from ``__args__``. On failure, an exception is raised and ``NULL`` is
returned.

Here's an example of how to make an extension type generic::

...
static PyMethodDef my_obj_methods[] = {
// Other methods.
...
{"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
...
}

.. seealso:: The data model method :meth:`__class_getitem__`.

.. versionadded:: 3.9

.. c:var:: PyTypeObject Py_GenericAliasType

The C type of the object returned by :c:func:`Py_GenericAlias`. Equivalent to
:class:`types.GenericAlias` in Python.

.. versionadded:: 3.9
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added a new section in the C API documentation for types used in type
hinting. Documented ``Py_GenericAlias`` and ``Py_GenericAliasType``.