There is a Python magic method __setitem__
for assignment =
to sequence types. Are there magic methods for augmented assignment +=
at the container level? The operation does appear to break down gracefully to an augmented assignment of the item-type. That's logical. But there's a magic method for almost everything else, I thought there should be a set of methods for these operators on a sequence type. Did I miss it?
The application is a kind of database. Think of implementing __getitem__
with a SELECT and __setitem__
with INSERT. There should be something like __additem__
etc. for UPDATE, right?
from __future__ import print_function
class Item(object):
def __init__(self, value):
self.value = value
def __str__(self):
return "Item " + str(self.value)
def __iadd__(self, other):
print("Item iadd", self, other)
return Item(self.value + "+" + other.value)
class Container(object):
def __getitem__(self, key):
print("Container getitem", key)
return Item(key)
def __setitem__(self, key, value):
print("Container setitem", key, value)
return self
def __additem__(self, key, value):
print("Container additem would be nice", key, value)
return self
Here's the SELECT:
>>> c = Container()
>>> _ = c['key']
Container getitem key
Here's the INSERT:
>>> c['key'] = Item('other')
Container setitem key Item other
How to implement UPDATE? Without breaking down into SELECT and INSERT:
>>> c['key'] += Item('other')
Container getitem key
Item iadd Item key Item other
Container setitem key Item key+other
So is there a way to implement augmented assignment differently than the broken-down steps? Without putting all the behavior in the Item class?
You can cut and paste the above code into python interpreter, or try it on this Python fiddle: http://pythonfiddle.com/add-item-for-sequence/
A related question shows the decompilation of self[key] += value