I want to create a class Packet
identical to list
except that it can be compared to int
objects. Comparing to an int
shall return the same result as comparing to a Packet
containing only that int
. The following definition does what I want.
class Packet(list):
def __init__(self, iterable=()):
super().__init__()
for x in iterable:
if isinstance(x, list):
self.append(type(self)(x))
else:
self.append(x)
def __lt__(self, x):
if isinstance(x, int):
return self.__lt__(type(self)([x]))
return super().__lt__(x)
def __le__(self, x):
if isinstance(x, int):
return self.__le__(type(self)([x]))
return super().__le__(x)
def __eq__(self, x):
if isinstance(x, int):
return self.__eq__(type(self)([x]))
return super().__eq__(x)
def __ne__(self, x):
if isinstance(x, int):
return self.__ne__(type(self)([x]))
return super().__ne__(x)
def __ge__(self, x):
if isinstance(x, int):
return self.__ge__(type(self)([x]))
return super().__ge__(x)
def __gt__(self, x):
if isinstance(x, int):
return self.__gt__(type(self)([x]))
return super().__gt__(x)
a = Packet([2, 3, 5])
b = Packet([[2], 3, [[5]]])
c = Packet([2, [3, 4]])
d = 2
assert a == b
assert a < c
assert a > d
assert b < c
assert b > d
assert c > d
However, this is rather repetitive; I wrote basically the same code six times. There's got to be a way to do this in a loop or at least using a decorator, right? How can I create an identical class without repeating myself?