Defining a Python enum in a C extension - am I doing this right?

MRAB python at mrabarnett.plus.com
Fri Jul 23 11:03:03 EDT 2021


On 2021-07-23 09:20, Bartosz Golaszewski wrote:
> Hi!
> 
> I'm working on a Python C extension and I would like to expose a
> custom enum (as in: a class inheriting from enum.Enum) that would be
> entirely defined in C.
> 
> It turned out to not be a trivial task and the regular mechanism for
> inheritance using .tp_base doesn't work - most likely due to the
> Enum's meta class not being pulled in.
> 
> Basically I'm trying to do this:
> 
[snip]
> 
> static PyObject *make_bases(PyObject *enum_mod)
> {
>      PyObject *enum_type, *bases;
> 
>      enum_type = PyObject_GetAttrString(enum_mod, "Enum");
>      if (!enum_type)
>          return NULL;
> 
>      bases = PyTuple_Pack(1, enum_type); /* Steals reference. */

PyTuple_Pack doesn't steal references, as far as I can tell.

>      if (!bases)
>          Py_DECREF(enum_type);
> 
>      return bases;
> }
> 
[snip]


More information about the Python-list mailing list