overriding __getitem__ for a subclass of dict

Jon Clements joncle at googlemail.com
Sun Nov 15 21:01:00 CET 2009

On Nov 15, 7:23 pm, Steve Howell <showel... at yahoo.com> wrote:
> On Nov 15, 10:25 am, Steve Howell <showel... at yahoo.com> wrote:
> > [see original post...]
> > I am most
> > interested in the specific mechanism for changing the __getitem__
> > method for a subclass on a dictionary.  Thanks in advance!
> Sorry for replying to myself, but I just realized that the last
> statement in my original post was a little imprecise.
> I am more precisely looking for a way to change the behavior of foo
> ['bar'] (side effects and possibly return value) where "foo" is an
> instance of a class that subclasses "dict," and where "foo" is not
> created by me.  The original post gives more context and example code
> that does not work as I expect/desire.

[quote from http://docs.python.org/reference/datamodel.html]
For instance, if a class defines a method named __getitem__(), and x
is an instance of this class, then x[i] is roughly equivalent to
x.__getitem__(i) for old-style classes and type(x).__getitem__(x, i)
for new-style classes.

A quick hack could be:

class Al(dict):
  def __getitem__(self, key):
    return self.spy(key)
  def spy(self, key):
    return 'Al'

>>> a = Al()
>>> a[3]
>>> a.spy = lambda key: 'test'
>>> a[3]
>>> b = Al()
>>> b[3]

Seems to be what you're after anyway...


More information about the Python-list mailing list