On 2006-07-20, Paul Boddie <[EMAIL PROTECTED]> wrote: > Alex Martelli wrote: >> Paul Boddie <[EMAIL PROTECTED]> wrote: >> > >> > Well, range is a function in the current implementation, although its >> > usage is similar to that one would get if it were a class, particularly >> > a subclass of list or one providing a list-style interface. With such a >> > class, you could provide a __contains__ method which could answer the >> > question of what the range contains based on the semantics guaranteed >> > by a range (in contrast to a normal list). >> >> You'd also have to override just about every mutating method to switch >> back to a "normal" __contains__ (or change self's type on the fly) -- a >> pretty heavy price to pay. > > A subclass of list is probably a bad idea in hindsight, due to various > probable requirements of it actually needing to be a list with all its > contents, whereas we wanted to avoid having anything like a list around > until the contents of this "lazy list" were required by the program. If > we really wanted to subclass something, we could consider subclassing > the slice class/type, but that isn't subclassable in today's Python for > some reason, and it doesn't really provide anything substantial, > anyway. However, Python being the language it is, an appropriately > behaving class is quite easily written from scratch.
Except that if you write your own class from scratch, you can't use it as a slice. For a language that is supposed to be about duck typing I find it strange that if I make my own class with a start, stop and step attribute, that python barfs on it when I want to use it as a slice. >>> class sl(object): ... def __init__(self, start = None, stop = None, step = None): ... self.start = start ... self.stop = stop ... self.step = step ... >>> lst = range(20) >>> s1 = slice(3,13) >>> s2 = sl(3,13) >>> s1.start 3 >>> s2.start 3 >>> s1.stop 13 >>> s2.stop 13 >>> s1.step >>> s2.step >>> lst[s1] [3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> lst[s2] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: list indices must be integers >>> -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list