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

Gerhard Häring gerhard.haering at gmx.de
Tue Aug 6 18:30:18 EDT 2002

* Travis Shirk <travis at pobox.com> [2002-08-06 22:11 -0000]:
> 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* does
> not allow non-int keys, and I assume that if I subclassed dict the reverse
> type clash would occur.  
> So, is there a way to "override" __getitem__ to accept both types of
> access?
Yes - from the PgResultSet class in the pyPgSQL sources:

def __getitem__(self, key):
    if type(key) is StringType:
        key = self.__class__._xlatkey[key]
    return self.baseObj[key]

If you're only targeting Python 2.2+ an isinstance(key, str) is a better

mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://www.cs.fhm.edu/~ifw00065/    OpenPGP public key id AD24C930
public key fingerprint: 3FCC 8700 3012 0A9E B0C9  3667 814B 9CAA AD24 C930
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))

More information about the Python-list mailing list