Lets say one wants to add item assignment to a class instance from a foreign library:
# defined outside our code base
class WeDoNotWantToDeriveThis(object): pass
inst = WeDoNotWantToDeriveThis()
def set_item_func(self, idx, val): print("hi there")
import types
# try to patch item setter
inst.__setitem__ = types.MethodType(set_item_func, inst)
assert hasattr(inst, '__setitem__')
print(type(inst.__setitem__)) # prints "instancemethod"
# try to perform item assignment on inst
inst[0] = None # raises 'object does not support item assignment'
The question is how to do this properly. Maybe 'setitem' is not looked up on the instance, but on the class itself to check whether the object does support item assignment?
According to the documentation, implementing the setitem method should be sufficient: https://docs.python.org/3/reference/datamodel.html#object.setitem
You have to set the instance method on the class:
>>> WeDoNotWantToDeriveThis.__setitem__ = types.MethodType(set_item_func, None, WeDoNotWantToDeriveThis)
>>> inst[0] = None
hi there
>>>