[Python-ideas] Implement comparison operators for range objects
Westley Martínez
anikom15 at gmail.com
Fri Oct 14 20:15:38 CEST 2011
On Wed, Oct 12, 2011 at 05:31:44PM +0100, 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
>
> To get a useful comparison, you would either need to realise both
> range objects as lists or use a function like
>
> def ranges_equal(r0, r1):
> if not r0:
> return not r1
> return len(r0) == len(r1) and r0[0] == r1[0] and r0[-1] == r1 [-1]
>
> 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.
>
> When implementing '==' and '!=' for range objects, it would be natural
> to implement the other comparison operators, too (lexicographically,
> as for all other sequence types). This change would be backwards
> incompatible, but I very much doubt there is much code out there
> relying on the current behaviour of considering two ranges as unequal
> just because they aren't the same object (and this code could be
> easily fixed by using 'is' instead of '==').
>
> Opinions?
>
I'm -32767 on this whole idea. It's not obvious what comparing a range
actually means, because a range is very abstract. If a developer needs
to compare ranges they should write their own functions to do it in
whatever way that fits their case.
More information about the Python-ideas
mailing list