range() is not the best way to check range?

Alex Martelli aleax at mac.com
Thu Jul 20 11:41:27 EDT 2006


Paul Boddie <paul at boddie.org.uk> wrote:

> Alex Martelli wrote:
> > Paul Boddie <paul at boddie.org.uk> 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.

Nevertheless, that class will still need to implement every single
method of the list type; making it a subclass of list has some advantage
in that every such implementation of a method can basically fill the
real list, self.__class__=list, and leave all the rest, forevermore
(explicitly here, implicitly in the future), to class list.  Performance
should be much better than by working off semi-deprecated UserList.

A "hook method" __mutator__ (ideally called _before_ in this case), as I
was proposing (for 2.6 or later), would make such approaches way easier
and handier (and would help with most use cases I can think of for
subclassing list, dict or set).


Alex



More information about the Python-list mailing list