Proposed new syntax

Ian Kelly ian.g.kelly at gmail.com
Tue Aug 22 09:42:51 EDT 2017


On Tue, Aug 22, 2017 at 3:58 AM, Stephan Houben
<stephanh42 at gmail.com.invalid> wrote:
> Op 2017-08-11, Paul Rubin schreef <no.email at nospam.invalid>:
>> I don't think we need this since we have itertools.takewhile:
>>
>>   from operator import gt
>>   from functools import partial
>>   from itertools import takewhile
>>
>>   [x + 1 for x in takewhile(partial(gt,5), (0,1,2,999,3,4))]
>>
>
> No need for partial and gt.
>
>   [x + 1 for x in takewhile((5).__gt__, (0,1,2,999,3,4))]
>
> Basically, Haskell's infix opererator sections can often be
> translated into Python by attribute access to the bound method.

Careful! Python's dunder methods are reserved for use by Python.
They're exposed so that we can override them. Calling them directly is
generally considered bad style. And in this case specifically, it's
not equivalent. Example:

import functools
import operator

@functools.total_ordering
class PseudoInt(object):
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
        return self.value == other
    def __lt__(self, other):
        return self.value < other

>>> PseudoInt(5) > 2
True
>>> 5 > PseudoInt(2)
True
>>> 5 > PseudoInt(7)
False
>>> operator.gt(5, PseudoInt(7))
False
>>> (5).__gt__(PseudoInt(7))
NotImplemented
>>> bool((5).__gt__(PseudoInt(7)))
True


The last line is the reason why the rich comparison methods should
have been designed to raise NotImplementedException rather than return
NotImplemented, but it's too late to change that.



More information about the Python-list mailing list