Slices as views, not copies (was Re: For Guido and developers Python.)

Jeff Epler jepler at unpythonic.net
Wed May 14 11:08:42 EDT 2003


If you need a view on a sequence, the best way to write it is a class.
No change in the language is needed.

Something like the following...

Jeff

class View:
    def __init__(self, l, start, stop):
        self.start = start
        self.stop = stop
        self.l = l

    def __getitem__(self, i):
        i = self.start + i
        if i >= self.stop:
            raise IndexError, "Index outside of view"
        return self.l[i]

    def __setitem__(self, i, v):
        i = self.start + i
        if i >= self.stop:
            raise IndexError, "Index outside of view"
        self.l[i] = v

    def __getslice__(self, start, stop):
        start = start + self.start
        stop = stop + self.start

        if start > self.stop: start = self.stop
        if stop > self.stop: stop = self.stop
            
        return View(self.l, start, stop)

    def __repr__(self):
        return "<%s@%x[%s:%s]>" % \
            (type(self.l).__name__, id(self.l), self.start, self.stop)

    def __str__(self):
        return "[" + ", ".join(
            [repr(self[i]) for i in range(self.stop-self.start)]) + "]"

    # fixme: add other sequence operations
    # fixme: handle negative indices
    # fixme: handle slices like [:3], [3:], [::2] etc
    # fixme: implement a read-only view

def _test():
    l = range(10)
    m = View(l, 3, 6)
    print l, m, repr(m)
    m[0] = "spam"
    n = m[1:2] # slicing gives a view
    n[0] = "spanish inquisition"
    print l, m, n


if __name__ == '__main__': _test()





More information about the Python-list mailing list