[Python-ideas] List Comprehensions

Michael Selik mike at selik.org
Mon Feb 8 18:54:37 EST 2016


On Wed, Feb 3, 2016 at 6:14 AM Chris Angelico <rosuav at gmail.com> wrote:

> On Wed, Feb 3, 2016 at 10:04 PM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> > I've sometimes thought that Python should have a iterator concatenation
> > operator (perhaps &) which we could use:
> >
> > [x for x in range(5) & [100] & "spam"]
> > => returns [0, 1, 2, 3, 4, 100, 's', 'p', 'a', 'm']
>
> Might be problematic for generic iterables, as your three examples
> are; but if you explicitly request an iterator, it's not hard to make
> it support + or & for chaining:
>
> from itertools import chain
>
> _iter = iter
> class iter:
>     def __init__(self, *args):
>         self.iter = _iter(*args)
>     def __add__(self, other):
>         return type(self)(chain(self.iter, _iter(other)))
>     __and__ = __add__
>     def __iter__(self): return self
>     def __next__(self): return next(self.iter)
>
> print(list(iter(range(5)) & [100] & "spam"))
>
> Is that good enough?
>

For some reason, the use of an operator there makes me feel like the
right-hand argument could be a non-iterable that is appended.

    ChainableRange(10) & [100]
    # versus
    ChainableRange(10) & 100

As opposed to the more explicit use of ``itertools.chain`` which makes it
more clear (in my head) that the second argument must be an iterable

    chain(range(10), [100])
    chain(range(10), 100)      # will cause TypeError: 'int' object is not
iterable


I could imagine a module of fancy iterables overloading __and__ for that
purpose, but it ought to be a large enough chunk of functionality to
warrant a mini-language. Like NumPy. As much as I dislike the term
"domain-specific language", I think this example of overloading operators
falls into that category. One could take the itertools module and map all
sorts of operators to its features:

    a & b       ==>     chain(a, b)
    it[j:k]     ==>     islice(it, j, k)
    +it         ==>     tee(it)
    a * b       ==>     product(a, b)
    2-it        ==>     pairwise(it)

etc. Not saying it's a good idea for the standard library, but I could see
a module that makes extensive use of itertools doing so. It's worth
repeating that I prefer using the word instead of the operator for most if
not all of these cases.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160208/cf497fdc/attachment.html>


More information about the Python-ideas mailing list