obj[1] *and* obj['foo']

Terry Reedy tjreedy at udel.edu
Wed Aug 7 00:34:51 CEST 2002

"Travis Shirk" <travis at pobox.com> wrote in message
news:ul0ich5k1nu27 at corp.supernews.com...
> I'm trying to write a class that implements __getitem__(self, k),
> but I'd like to invoke the method with integer keys and string keys.
> Currently, I'm getting exceptions when I use string keys:
> TypeError: sequence index must be integer
> I'm subclassing list (python 2.2) so I understand why the *sequence*
> not allow non-int keys, and I assume that if I subclassed dict the
> type clash would occur.

No, dict (or subclass thereof) is happy with any hashable as key.  It
would be up to you to intercept ints and convert to string via
auxiliary list.  (Or double key all values!).

Alternative is list subclass with string access via attribute rather
than key.  To do this, write appropriate __get/setattr__ and use
auxiliary dict to convert string to index.

IE listdict[0] == listdict.happy, listdict[1] == listdict.sad, etc.  I
believe something like this done in standard lib (os module or sub

Terry J. Reedy

More information about the Python-list mailing list