Greater and less than operators [was Re: [Tutor] beginning to code]

Rick Johnson rantingrickjohnson at gmail.com
Wed Sep 20 20:16:23 EDT 2017


Steven D'Aprano wrote:
> Rick Johnson wrote:
> 
> > Of course, allowing all objects to use the `==`, `!=`
> > sugars makes perfect sense, but `<`, `>`, `<=`, `>=` are
> > meaningless outside of numeric-ish types.
> 
> You've never wanted to sort strings? How do you sort
> strings unless you have a concept of which string comes
> before the other, i.e. < operator?
> 
> >>> 'xyz' < 'abc'
> False

Interesting. But now we need to learn yet another set of
arbitrary rules. Consider this:

    >>> 'azzz' > 'zzz'
    False
    
Now, i'm not sure how Python decided that 'azzz' is not
greater than 'zzz' (and not because 'azzz' has a length of
4!) , unless of course, Python is comparing the chars
positionally and then discarding the fourth 'z' (a la zip()
function behavior), but if we sum the chars in those strings
using the return value of `ord()`, this is what we get:

    >>> sum(map(ord, 'azzz'))
    463
    >>> sum(map(ord, 'zzz'))
    366

And now we can make it a one liner:

    >>> sum(map(ord, 'azzz')) > sum(map(ord, 'zzz'))
    True

Ah. That's much more intuitive. And i just hate when my
Python tells lies. ;-)

> Same applies to lists of items. Provided the items are
> compatible with ordering, so are the lists. Likewise other
> sequences.

But how are we to intuit the arbitrary rules?

> And for that matter, sets. Maybe we'd prefer to use the
> proper mathematical operators ⊂ and ⊃ for subset and
> superset, but a good ASCII equivalent would be < and >
> instead.

A reasonable point, i admit.

> Likewise, any time you want to express some sort of order
> relationship:
> 
> pawn < rook < knight < bishop < queen < king

Yes, but in this case the programmer would have to
explicitly override some rich comparison dunders and the
source code would reveal the rules.

> Or perhaps you have some sort of custom DSL (Domain
> Specific Language) where > and < make handy symbols for
> something completely unrelated to ordering:
> 
> cake > oven  # put cake into the oven
> 
> cake < oven  # remove cake from oven

That's a highly contrived example and not something that
looks like a good idea. A better solution would be to create
an Oven object that only accepts certain types of "bake-
ables": like cakes, pies or a Turducken.[1] 

[1] Now, that's not only duck typing, it's also duc[tk]
stuffing (pun intended!).



More information about the Python-list mailing list