[Python-ideas] Implement comparison operators for range objects
Guido van Rossum
guido at python.org
Wed Oct 12 19:41:09 CEST 2011
On Wed, Oct 12, 2011 at 10:33 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> Sven Marnach wrote:
>>
>> There are circumstances, for example in unit testing, when it might be
>> useful to check if two range objects describe the same range.
>> Currently, this can't be done using the '==' operator:
>>
>> >>> range(5) == range(5)
>> False
>
> [...]
>>
>> All other built-in sequence types (that is bytearray, bytes, list,
>> str, and tuple) define equality by "all items of the sequence are
>> equal". I think it would be both more consistent and more useful if
>> range objects would pick up the same semantics.
>
> I can see how that would be useful and straightforward, and certainly more
> useful than identity based equality. +1
+1
>> 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. 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.
>
> Which is greater?
>
> range(1, 1000000, 1000)
> range(1000, 10000)
>
> The question makes no sense, and should be treated as an error, just as it
> is for complex numbers.
>
> -1 on adding order comparison operators.
Agreed.
> Aside:
>
> I'm astonished to see that range objects have a count method! What's the
> purpose of that? Any value's count will either be 0 or 1, and a more
> appropriate test would be `value in range`:
>
>>>> 17 in range(2, 30, 3) # like r.count(17) => 1
> True
>>>> 18 in range(2, 30, 3) # like r.count(18) => 0
> False
Probably because some ABC has it.
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list