I have the following piece of code that was already written by someone else which implements the "enumerated" type like in C, but the code is failing in __cmp__
function with the error:
assert self.EType is other.EType,
AttributeError: 'str' object has no attribute 'EType'
Could you please let me have some suggestions how to make the comparison between a str
and an EType
objects, to fix the error?
def enum(*parameters):
assert parameters, "Empty enums are not supported"
class EClass(object):
""" Internal class """
__slots__ = parameters
def __iter__(self):
return iter(constants)
def __len__(self):
return len(constants)
def __getitem__(self, i):
return constants[i]
def __repr__(self):
return 'Enum' + str(parameters)
def __str__(self):
return 'enum ' + str(constants)
class EValue(object):
""" Internal class """
__slots__ = '__value'
def __init__(self, value):
self.__value = value
Value = property(lambda self: self.__value)
EType = property(lambda self: EType)
def __hash__(self):
return hash(self.__value)
def __cmp__(self, other):
assert self.EType is other.EType, \
"Only values from the same enum are comparable"
return cmp(self.__value, other.__value)
def __invert__(self):
return constants[maximum - self.__value]
def __nonzero__(self):
return bool(self.__value)
def __repr__(self):
return str(parameters[self.__value])
maximum = len(parameters) - 1
print ("maximum %d") % maximum
constants = [None] * len(parameters)
for i, each in enumerate(parameters):
val = EValue(i)
setattr(EClass, each, val)
constants[i] = val
constants = tuple(constants)
EType = EClass()
return EType
if __name__ == "__main__":
call_type = "test1"
if call_type not in enum('test1', 'test2'):
print 1