[Python-ideas] Implement comparison operators for range objects

Sven Marnach sven at marnach.net
Wed Oct 12 18:31:44 CEST 2011


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?

 -- Sven



More information about the Python-ideas mailing list