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

Bartosz Golaszewski brgl at bgdev.pl
Mon Jul 26 03:28:04 EDT 2021


On Sat, Jul 24, 2021 at 6:55 AM Dan Stromberg <drsalists at gmail.com> wrote:
>
>
> On Fri, Jul 23, 2021 at 1:20 AM Bartosz Golaszewski <brgl at bgdev.pl> 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.
>
>
> I'm probably missing something obvious, but why would you write new code in C when you can just use Cython?  Cython is a lot easier, and quite fast, and should (eventually?) allow compiling to HPY instead of just "the" C extension module interface.
>
> https://news.ycombinator.com/item?id=26627683
>

I'm the author and maintainer of libgpiod - the user-space library and
tools for using the linux GPIO character device.

The core library is written in C but we're also exposing C++ and
Python bindings (with more language bindings planned). The python
bindings are written as a C extension module and look like this:
https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/bindings/python/gpiodmodule.c.

We're in the process of writing the (backward incompatible) version 2
of the library in order to support the new kernel features and the C
API has changed a lot so we're also rewriting the bindings. Among
others: all bitwise flags have now been converted to enums, hence my
question. In C++ we'll use scoped enum classes and I'd like to do a
similar thing in python.

What I'm doing is not aimed at using C for speed but for calling the C
APIs. I know I could use SWIG but in order to make the interface
elegant, it would have to be packaged in proper Python classes anyway,
creating another layer of code so I prefer to just use C.

Bart


More information about the Python-list mailing list