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

Christopher A. Craig list-python at ccraig.org
Wed Aug 7 13:01:00 EDT 2002

Jonathan Hogg <jonathan at onegoodidea.com> writes:

> The problem with subclassing list is that you end up in the dark world of
> Python C-type prototols where sequences and mappings are different things.
> The type subclassing magic fakes up what looks like a standard __getitem__
> call, except by that point it's too late and you've been forced through the
> sequence protocol and the argument must be an integer.

Subclassing list doesn't actually effect what inputs you can take in

Python 2.2.1 (#2, Apr 22 2002, 17:53:10) 
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(list):
...   def __getitem__(self, key):
...     if type(key)==type(1): 
...       return list.__getitem__(self, key)
...     elif type(key)==type('a') and len(key)==1 and 'a'<=key<='z': 
...       return list.__getitem__(self, ord(key)-ord('a'))
...     else:
...       raise TypeError, "sequence index must be integer"
>>> t = Foo()
>>> t.append(3)
>>> t[0]
>>> t['a']
>>> t[1.]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: sequence index must be integer

That said, if you want to use strings as indexes you probably want a

Christopher A. Craig <list-python at ccraig.org>
"I wouldn't be surprised if the architecture of Intel's microprocessors
were eventually linked to the eventual fall of mankind." Steve Gibson

More information about the Python-list mailing list