I have a class Message and a class MessageCollection which obviously depends on Message. I'd like to do this:
m1 = Message()
m2 = Message()
collection = m1 + m2
isinstance(collection, MessageCollection) # True
The problem is that I have to overload __add__ operator in Message class and create a new MessageCollection instance there:
class Message:
def __add__(self, msg_or_collection):
if isinstance(msg_or_collection, Message):
return MessageCollection([self, msg_or_collection])
elif isinstance(msg_or_collection, MessageCollection)
return msg_or_collection.append(self)
raise TypeError("can't add %s to Message" % type(msg_or_collection))
thus creating an ugly circular dependency. Is there any way to avoid it? Maybe my design is wrong and there are other approaches to this?
EDIT:
I already have overloaded MessageCollection's __add__operator indeed, so I can do
collection1 = MessageCollection()
collection2 = collection1 + m1 + m2.
I just want to make it a bit nicer...
EDIT 2:
I eventually removed the dependency and left the Message class without the __add__ overloading.
However.... I've been thinking about it and to me it makes perfect sense to have the syntax collection_of_objects = object1 + object2. It expresses the notion of "I had an apple, then I bought another one, so now I have a collection of two apples". Maybe we should think of an object being a special case of a collection where the number of objects is 1? In this case, the object should inherit from (or be decorated by) a "listable" class...
anyway, thanks for your answers folks! I'll leave the question open to see if it generates further debate ;)
m1 + m2to create aMessageCollection, but you don't wantMessageto depend onMessageCollection? Impossible.m1 + m2returning aMessageCollectionis nicer. Because it will tightly coupleMessageCollectionto 'Message' preventing you from using other types of containers in the future or even from ever extending MessageCollection. Having__add__on MessageCollection is the correct way to go__add__would prevent me from using other containers