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

Paul Boddie paul at boddie.org.uk
Tue Jul 18 08:24:32 EDT 2006


John Machin wrote:
>
> range() and xrange() are functions. You are suggesting that 2
> *functions* should acquire a __contains__ method each? I trust not.

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).

> Perhaps you meant that the acquisitors should be the objects that those
> functions return.

The whole point was to avoid expanding the range into a list.

[...]

> A __contains__ method for xrange objects? The case of x in xrange(lo,
> hi) is met by lo <= x < hi. IMHO, anyone who wants x in xrange(lo, hi,
> step) should be encouraged to do the necessary algebra themselves; I
> wouldn't suggest that any core dev time be wasted on implementing such
> folderol.

Sure, you could always implement your own class to behave like an
existing range and to implement the efficient semantics proposed above.

> In any case, isn't the *whole* xrange gizmoid on GvR's I-wish-I-hadn't list?

Yes, he wants range to return an iterator, just like xrange more or
less does now. Given that xrange objects support __getitem__, unlike a
lot of other iterators (and, of course, generators), adding
__contains__ wouldn't be much of a hardship. Certainly, compared to
other notational conveniences bounced around on the various development
lists, this one would probably provide an order of magnitude
improvement on the usual bang per buck development ratio.

Paul




More information about the Python-list mailing list