[Python-ideas] + operator on generators

David Mertz mertz at gnosis.cx
Tue Jun 27 15:27:25 EDT 2017


On Tue, Jun 27, 2017 at 4:44 AM, Steven D'Aprano <steve at pearwood.info>
wrote:

> But that strikes me as overkill. You don't normally check for dunders
> before using an operator, and we already have operators that can return
> different types depending on the operands:
>
> % can mean modulo division or string interpolation
> * can mean sequence repetition or numeric multiplication
> + can mean numeric addition or sequence concatenation
>
> Why is
>
> & can mean iterable chaining or bitwise-AND
>

I don't think it's "uniquely confusing."  Just more so than the other
examples you give.  For example, I might write functions like these
(untested):

    def modulo1(i: int, j: int) -> int:
        return i % j

    def modulo2(s: str, t: tuple) -> str:
        return s % t

And similar examples for `*` and `+`.  When I try to write this:

    def ampersand(x: Iterable, y: Iterable) -> Iterable:
        return x & y

More ambiguity exists.  The type signature works for both Numpy arrays and
generators (under the proposed language feature), but the function does
something different... in a way that is "more different" than I'd expect.

That said, I like the idea of having iterators that act magically to fold
in general iterables after an .__and__() or .__add__() as proposed by
Brendan down-thread.  Without any language change we could have:

    chainable(x for x in blah) + [1, 2, 3] + "hello"

And I would like a language change that made a number of common iterable
objects "chainable" without the wrapper.  This wrapper could of course be
used as a decorator too.

E.g. generator comprehensions, things returned by itertools functions,
range(), enumerate(), zip(), etc.  This wouldn't promise that EVERY
iterable or iterator had that "chainable" behavior, but it would cover 90%
of the use cases.  And I wouldn't find it confusing because the leftmost
object would be the one determining the behavior, which feels more
intuitive and predictable.

I don't hate `&&`, but I think this approach makes more sense.

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170627/be8b0949/attachment.html>


More information about the Python-ideas mailing list