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

Bartosz Golaszewski brgl at bgdev.pl
Fri Jul 23 13:26:58 EDT 2021


On Fri, Jul 23, 2021 at 5:08 PM MRAB <python at mrabarnett.plus.com> wrote:
>
> 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.
>

Right, the doc says it's equivalent to Py_BuildValue("(OO...)", ...)
and it does increase the reference count on stored objects. It doesn't
answer the main question though. :)

Bartosz

> >      if (!bases)
> >          Py_DECREF(enum_type);
> >
> >      return bases;
> > }
> >
> [snip]
> --
> https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list