pythonmonkeypatching

Is it possible to override __getitem__ at instance level in Python?


With the following code :

import types

class Foo():
    def __getitem__(self, x):
        return x

def new_get(self, x):
    return x + 1

x = Foo()
x.__getitem__ = types.MethodType(new_get, x)

x.__getitem__(42) will return 43, but x[42] will return 42.

Is there a way to override __getitem__ at instance level in Python?


Solution

  • This is unfortunately, and quite surprisingly, not allowed:

    For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

    Source: https://docs.python.org/3/reference/datamodel.html#special-lookup