Comparing fragments in python

By checking the class slicein Python with dir(), I see that it has attributes __le__and __lt__. Indeed, I saw that the following code works:

slice(1, 2) < slice(3, 4)
# True

However, I do not see what logic is implemented for this comparison, and not its use. Can someone point me to this?

I'm not asking about comparing a tuple. Even if the slice and tuple are compared the same way, I don't think this makes my question a duplicate. What more, I also asked for a possible slice comparison assembly that the proposed duplicate did not offer.

+4
source share
3 answers

: (1, 2) < (3, 4) True, (1, 2) comes before (3, 4).

(1, 2) < (0, 4) False, (1, 2) comes after (0, 4).

NB: < > smaller than greater than, is before is after.

, , , .

"" ( < >):

(1, 2) < (3, 4, 5) True, nil , . , (1, 2) come before (3, 4, 5).

(0, 1) < (1, 0) True, (0, 1) comes before (1, 0)

:

(0, 1, 20000) < (0, 3, 1) True, (0, 1, 20000) comes before (0, 3, 1).

slice, list strings.

. .

+2

Python , . .

@NPE, CPython , slice (start, end, step). Python, , :

vals = []
for a in range(-5, 5):
    for b in range(-5, 5):
        for c in range(-5, 5):
            vals.append((a, b, c))
for x in vals:
    for y in vals:
        assert (slice(*x) < slice(*y)) == (x < y)

. , Jython , -. , , id s, .

, Jython . , True True Jython True False CPython:

print(slice(1, 2) < slice(1, 3))
print(slice(1, 3) < slice(1, 2))

Summing up: __lt__implemented in CPython for some unclear reason, but it is not described anywhere in the documentation and other implementations can behave not only differently, but also “incorrectly” (in mathematical sense ). Therefore, slices should not be compared for inequality.

+2
source

Source: https://habr.com/ru/post/1679334/


All Articles