overriding __getitem__ for a subclass of dict

Steve Howell showell30 at yahoo.com
Sun Nov 15 20:29:38 CET 2009


On Nov 15, 11:19 am, Gary Herron <gher... at islandtraining.com> wrote:
> Steve Howell wrote:
> > I ran the following program, and found its output surprising in one
> > place:
>
> >     class OnlyAl:
> >         def __getitem__(self, key): return 'al'
>
> >     class OnlyBob(dict):
> >         def __getitem__(self, key): return 'bob'
>
> >     import sys; print sys.version
>
> >     al = OnlyAl()
> >     bob = OnlyBob()
>
> >     print al['whatever']
> >     al.__getitem__ = lambda key: 'NEW AND IMPROVED AL!'
> >     print al['whatever']
>
> >     print bob['whatever']
> >     bob.__getitem__ = lambda key: 'a NEW AND IMPROVED BOB seems
> > impossible'
> >     print bob['whatever']
>
> >     2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> >     [GCC 4.3.3]
> >     al
> >     NEW AND IMPROVED AL!
> >     bobe
> >     bob
>
> It's the difference between old-style and new-style classes.  Type dict
> and therefore OnlyBob are new style.  OnlyAl defaults to old-style.  If
> you derive OnlyAl from type object, you'll get consistent results.
>

Thanks, Gary.  My problem is that I am actually looking for the
behavior that the old-style OnlyAl provides, not OnlyBob--allowing me
to override the behavior of al['foo'] and bob['foo'].  I (hopefully)
clarified my intent in a follow-up post that was sent before I saw
your reply.  Here it is re-posted for convenience of discussion:

"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."





More information about the Python-list mailing list