Archived

This forum has been archived. Please start a new discussion on GitHub.

IcePy: Check types in generated compare methods

(Using Ice 3.3.1 on Linux)

Consider this Slice definition:
module Demo {
    struct Value {
        float v;
    };
};

Now observe this Python session:
>>> from Demo import *
>>> l = ['a', 5, Value(2.0)]
>>> 'a' in l
True
>>> 5 in l
True
>>> Value(2.0) in l
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "Demo_ice.py", line 36, in __cmp__
    if self.v < other.v:
AttributeError: 'str' object has no attribute 'v'

This is because the Value.__cmp__() method generated by slice2py tries to access the 'v' member of the right-hand-side object even though it may not have one:
def __cmp__(self, other):
            if other == None:
                return 1
            if self.v < other.v:
                return -1
            elif self.v > other.v:
                return 1
            return 0

The code should check the type of 'other' before accessing 'Value'-specific members:
def __cmp__(self, other):
            if other == None:
                return 1
            if not isinstance(other, _M_Demo.Value):
                return NotImplemented
            if self.v < other.v:
                return -1
            elif self.v > other.v:
                return 1
            return 0

With the comparison fixed like this, the example works as expected:
>>> 'a' in l
True
>>> 5 in l
True
>>> Value(2.0) in l
True
>>> Value(2.5) in l
False

Comments

  • matthew
    matthew NL, Canada
    Thanks for the report. We'll consider this for the next release.