Objects for Type Hinting

Various built-in types for type hinting are provided. Only GenericAlias is exposed to C.

PyObject* Py_GenericAlias(PyObject \origin, PyObject *args*)

Create a GenericAlias object. Equivalent to calling the Python class types.GenericAlias. The origin and args arguments set the GenericAlias‘s __origin__ and __args__ attributes respectively. origin should be a PyTypeObject*, and args can be a 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:

  1. ...
  2. static PyMethodDef my_obj_methods[] = {
  3. // Other methods.
  4. ...
  5. {"__class_getitem__", (PyCFunction)Py_GenericAlias, METH_O|METH_CLASS, "See PEP 585"}
  6. ...
  7. }

参见

The data model method __class_getitem__().

3.9 新版功能.

PyTypeObject Py_GenericAliasType

The C type of the object returned by Py_GenericAlias(). Equivalent to types.GenericAlias in Python.

3.9 新版功能.