[Python-ideas] Implement comparison operators for range objects

Guido van Rossum guido at python.org
Thu Oct 13 03:06:54 CEST 2011


On Wed, Oct 12, 2011 at 5:22 PM, David Townshend <aquavitae69 at gmail.com> wrote:
>
> On Oct 12, 2011 9:37 PM, "Sven Marnach" <sven at marnach.net> wrote:
>>
>> Steven D'Aprano schrieb am Do, 13. Okt 2011, um 04:33:49 +1100:
>> > >When implementing '==' and '!=' for range objects, it would be natural
>> > >to implement the other comparison operators, too (lexicographically,
>> > >as for all other sequence types).
>> >
>> > I don't agree. Equality makes sense for ranges: two ranges are equal
>> > if they have the same start, stop and step values.
>>
>> No, two ranges should be equal if they represent the same sequence,
>> i.e. if they compare equal when converted to a list:
>>
>>    range(0) == range(4, 4, 4)
>>    range(5, 10, 3) == range(5, 11, 3)
>>    range(3, 6, 3) == range(3, 4)
>>
>> > But order
>> > comparisons don't have any sensible meaning: range objects are
>> > numeric ranges, integer-valued intervals, not generic lists, and it
>> > is meaningless to say that one range is less than or greater than
>> > another.
>>
>> Well, it's meaningless unless you define what it means.  Range objects
>> are equal if they compare equal after converting to a list.  You could
>> define '<' or '>' the same way.  All built-in sequence types support
>> lexicographical comparison, so I thought it would be natural to bring
>> the only one that behaves differently in line.  (Special cases aren't
>> special enough...)
>>
>> This is just to explain my thoughts, I don't have a strong opinion on
>> this one.
>>
>> I'll try and prepare a patch for '==' and '!=' and add it to the issue
>> tracker.
>>
>> Cheers,
>>    Sven
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> http://mail.python.org/mailman/listinfo/python-ideas
>
> If you consider a range to represent a special type of set, which it is
> since it always contains unique values, then comparison operators do make
> sense. E.g. range(4,8) < range(2,9) is a subset comparison.

But it's *not* a set. It's got a definite order. range(10) != range(9,
-1, -1) even though they contain the same values.

> +1 for equality checks

Yeah, we're down to bikeshedding about whether range(0, 10, 2) ==
range(0, 11, 2).

-- 
--Guido van Rossum (python.org/~guido)



More information about the Python-ideas mailing list