emulating sequences

John Hunter jdhunter at nitace.bsd.uchicago.edu
Fri Aug 31 18:00:04 CEST 2001

>>>>> "Hans" == Hans Nowak <hnowak at cuci.nl> writes:

    Hans> Yes. You only need __getitem__:

    >>>> class Seq:
    Hans> 	def __init__(self, seq): self.seq = seq def
    Hans> __getitem__(self, index): return self.seq[index]

    >>>> s = Seq("cocoricoo") for c in s: print c,

    Hans> c o c o r i c o o

Thanks for the reply.  I think you also need to raise the IndexError
exception as well, as Alex pointed out.  I think your example relies
on 'seq' to raise that exception for it.  No?  In my case, I am
wrapping the c++ std::vector<type> as a python extension, so I have to
raise that exception myself.  I did implement __getitem__ but the 'in'
loop never terminates, so now I have to figure out how to raise the
right exception from C++.

John Hunter

More information about the Python-list mailing list