Change enum to yield integers values instead of strings

Issue #55 resolved
Amaury Forgeot d'Arc
created an issue

The enum below comes from libxml2.

typedef enum {
    XML_ERR_NONE = 0,
    XML_ERR_ERROR = 2,
} xmlErrorLevel;

cffi currently returns values as strings: "XML_ERR_WARNING", for example. But numeric values are often more indicated. For example, code like this (copied from lxml) is difficult to write with cffi:

if c_ctxt.lastError.level < xmlerror.XML_ERR_ERROR:

Returning enum as strings has only a small advantage: to type "XML_ERR_ERROR" instead of mylib.XML_ERR_ERROR. but enums are really numbers!

Yes, I understand this is an incompatible change. The input converter could still accept both strings and ints.

Comments (3)

  1. Armin Rigo

    For enums that are meant to be used as ints, you can already not define them as enums at all. You can say

    typedef int xmlErrorLevel;
    #define XML_ERR_NONE ...
    and so on

    I think it is enough to have the ability to declare enums as either enums (when we really want only the names) or #defines (when the numeric values are useful). Maybe this point should be documented?

  2. Armin Rigo

    Alternatively, how about returning instances of a subclass of int? It would be similar to how bool is a subclass of int. They would behave like ints except for repr() and str().

  3. Log in to comment