4 ms·
def __add__(self, other): if isinstance(other, dict): new = type(self)() # May be a subclass of dict. new.update(self)
by mroche 8y ago
def __add__(self, other):
if isinstance(other, dict):
new = type(self)() # May be a subclass of dict.
new.update(self)
new.update(other)
return new
Is there something I’m missing? To me it would be cleaner and more memory/time performant to just `self.update(other)` rather than having a third list instance at operation time. But that would really only apply if you have truly massive dicts.
- Znafon 8y agoYes, Python supports in place operators to avoid this: def __iadd__(self, other): if isinstance(other, dict): self.update(other) return self This would get called for `d += other`.
- mroche 8y agoMy follow up question would be why not do this for both union functions? I don’t see why they would want to have two functions that do the exact same thing (called differently, though) be written in two different ways.