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

Serhiy Storchaka storchaka at gmail.com
Fri Aug 6 03:45:38 EDT 2021


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.

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:

__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().



More information about the Python-list mailing list