[Tutor] overriding brackets in lvalue assignment possible?

James Hartley jjhartley at gmail.com
Tue Dec 27 11:48:00 EST 2016

I can successfully override __getitem__() for rvalues, but the following
example shows that more is required when used as an lvalue:

#!/usr/bin/env python

class Foo():
    def __init__(self, n):
        self.d = dict.fromkeys([i for i in range(0, n)])

    def __getitem__(self, i):
        return self.d[i]

def main():
    foo = Foo(4)
    foo[0] = 2               # not as an lvalue?

if __name__ == '__main__':

Python 3.4 generates the following output when this example is executed:

Traceback (most recent call last):
  File "./test.py", line 17, in <module>
  File "./test.py", line 13, in main
    foo[0] = 2
TypeError: 'Foo' object does not support item assignment

I am surprised that the error states that the object itself cannot accept
assignment.  From the C++ perspective, the underlying dictionary should be
exposed.  Does Python overloading allow use of bracket overriding in


More information about the Tutor mailing list