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

Bartosz Golaszewski brgl at bgdev.pl
Sun Aug 8 15:24:21 EDT 2021


On Fri, Aug 6, 2021 at 9:02 PM Serhiy Storchaka <storchaka at gmail.com> wrote:
>
> 03.08.21 13:03, Bartosz Golaszewski пише:
> > Just a follow-up: this is how I did it eventually:
>
> I think it can be simpler.
>
> 1. No need to create the __main__ module. You can just create a dict. If
> some attributes are required (e.g. __name__) it is easy to set them in
> the Python code (__name__ = 'pycenum').
>
> 2. No need to import the enum module in the C code. It is easier to do
> it in the Python code.
>

Don't you need the '__import__' attribute for that? It's linked to point #1.

> 3. Can you define your DummyType in the Python code instead of the C
> code? Even if you need to create in the C code, it may be better to
> define your enum class inside a dummy DummyType. It will set correct
> __qualname__ of the enum class:
>

This code is a PoC for the real code I want to use it in where the
type embedding the enum is defined in C.

> __name__ = 'pycenum'
> import enum
> class DummyType:
>     class FooBar(enum.Enum):
>         ...
>
> 4. Did you consider idea of making DummyType a heap-allocated type? It
> may be easy to create new type with PyType_FromModuleAndSpec(), and it
> is more stable API, and the type is not immutable, so it is easy to add
> new attributes with PyObject_SetAttrString().
>

Makes sense, thanks, I'll try it.

Bart


More information about the Python-list mailing list