[Python-ideas] Need feedback about exposing an operator overloading in a module
Terry Reedy
tjreedy at udel.edu
Tue Oct 21 03:29:59 CEST 2014
On 10/20/2014 3:42 PM, Julien Palard wrote:
> Hi everybody,
>
> Long long time ago, I wrote thehttps://pypi.python.org/pypi/pipe
> Python module, TL;DR: a 6 lines of code decorator enabling infix
> syntax.
>
> Long time ago someone came to speak to me on IRC advising me to speak
> about it here, but I was still blocked in my mind about the
> exposed/leaked `|` operator overload. For me, a module should never
> expose an operator overload, because it may lead to
> unpredicted/unnatural/surprising behavior. But I may be wrong.
>
> Recently I was thinking about my pipe module and got an idea: What
> about exposing a single function instead of a whole bunch of
> operator-overloaded functions ? Like Pipe (because I can't spot a real
> name for the moment but need one for the example) and translate from:
>
> fib() | pp.where(lambda x: x % 2 == 0)
> | pp.take_while(lambda x: x < 4000000)
> | pp.add
>
> to
>
> Pipe(fib()).where(lambda x: x % 2 == 0)
> .take_while(lambda x: x < 4000000)
> .add().data
>
> It's a bit more dense but still far more readable than the
> classic suffix notation:
>
> pp.add(pp.take_while(lambdax: x < 4000000,
> pp.where(lambda x: x % 2 == 0, fib())))
I think the best is current idiomatic python:
import itertools as it
def fibg():
a,b = 0, 1
while True:
yield a
a,b = b, a+b
evenfib = filter(lambda x: not x % 2, fibg())
print(sum(it.takewhile(lambda x: x < 4000000, evenfib)))
>>>
4613732
Two lines instead of three, with meaning clear. I am a fan of
abstraction by naming and like breaking paragraphs up into sentences,
and suites into statements.
> 1) Do you think, like me, that exposing a `|` overload is bad ?
No.
> 3) Do you want to see something permitting infix notation in Python
> standard library ?
Not especially. More persuasive use case needed.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list