Skip to content

Commit c7e9571

Browse files
[3.9] bpo-44392: Add Py_GenericAlias to C API docs (GH-26724) (GH-26757)
(cherry picked from commit 6773c3e)
1 parent 8fe57aa commit c7e9571

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

Doc/c-api/concrete.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,3 +115,4 @@ Other Objects
115115
coro.rst
116116
contextvars.rst
117117
datetime.rst
118+
typehints.rst

Doc/c-api/typehints.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
.. highlight:: c
2+
3+
.. _typehintobjects:
4+
5+
Objects for Type Hinting
6+
------------------------
7+
8+
Various built-in types for type hinting are provided.
9+
Only :ref:`GenericAlias <types-genericalias>` is exposed to C.
10+
11+
.. c:function:: PyObject* Py_GenericAlias(PyObject *origin, PyObject *args)
12+
13+
Create a :ref:`GenericAlias <types-genericalias>` object.
14+
Equivalent to calling the Python class
15+
:class:`types.GenericAlias`. The *origin* and *args* arguments set the
16+
``GenericAlias``\ 's ``__origin__`` and ``__args__`` attributes respectively.
17+
*origin* should be a :c:type:`PyTypeObject*`, and *args* can be a
18+
:c:type:`PyTupleObject*` or any ``PyObject*``. If *args* passed is
19+
not a tuple, a 1-tuple is automatically constructed and ``__args__`` is set
20+
to ``(args,)``.
21+
Minimal checking is done for the arguments, so the function will succeed even
22+
if *origin* is not a type.
23+
The ``GenericAlias``\ 's ``__parameters__`` attribute is constructed lazily
24+
from ``__args__``. On failure, an exception is raised and ``NULL`` is
25+
returned.
26+
27+
Here's an example of how to make an extension type generic::
28+
29+
...
30+
static PyMethodDef my_obj_methods[] = {
31+
// Other methods.
32+
...
33+
{"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
34+
...
35+
}
36+
37+
.. seealso:: The data model method :meth:`__class_getitem__`.
38+
39+
.. versionadded:: 3.9
40+
41+
.. c:var:: PyTypeObject Py_GenericAliasType
42+
43+
The C type of the object returned by :c:func:`Py_GenericAlias`. Equivalent to
44+
:class:`types.GenericAlias` in Python.
45+
46+
.. versionadded:: 3.9
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Added a new section in the C API documentation for types used in type
2+
hinting. Documented ``Py_GenericAlias`` and ``Py_GenericAliasType``.

0 commit comments

Comments
 (0)