Ticket #2744: enum_with_duplicated_values_v2.patch

File enum_with_duplicated_values_v2.patch, 1.3 KB (added by hugo.lima@…, 14 years ago)

Create a new attribute called "names" that maps the name of enum to their value and fix the "enum with duplicated values" bug.

  • libs/python/src/object/enum.cpp

    (this hunk was shorter than expected)  
    139139      dict d;
    140140      d["__slots__"] = tuple();
    141141      d["values"] = dict();
     142      d["names"] = dict();
    142143
    143144      object module_name = module_prefix();
    144145      if (module_name)
     
    186187
    187188    dict d = extract<dict>(this->attr("values"))();
    188189    d[value] = x;
    189190   
    190191    // Set the name field in the new enum instanec
    191192    enum_object* p = downcast<enum_object>(x.ptr());
    192193    Py_XDECREF(p->name);
    193194    p->name = incref(name.ptr());
     195
     196    dict names_dict = extract<dict>(this->attr("names"))();
     197    names_dict[x.attr("name")] = value;
    194198}
    195199
    196200void enum_base::export_values()
    197201{
    198     dict d = extract<dict>(this->attr("values"))();
    199     list values = d.values();
     202    dict d = extract<dict>(this->attr("names"))();
     203    list items = d.items();
    200204    scope current;
    201205   
    202     for (unsigned i = 0, max = len(values); i < max; ++i)
    203     {
    204         api::setattr(current, object(values[i].attr("name")), values[i]);
    205     }
     206    for (unsigned i = 0, max = len(items); i < max; ++i)
     207        api::setattr(current, items[i][0], items[i][1]);
    206208 }
    207209
    208210PyObject* enum_base::to_python(PyTypeObject* type_, long x)