[Python-ideas] Accessing the result of comprehension's expression from the conditional

Chris Rebert pyideas at rebertia.com
Fri Jun 19 23:05:49 CEST 2009

On Fri, Jun 19, 2009 at 12:56 PM, Mathias
Panzenböck<grosser.meister.morti at gmx.net> wrote:
> Chris Rebert wrote:
>> On Fri, Jun 19, 2009 at 10:54 AM, Mathias
>> Panzenböck<grosser.meister.morti at gmx.net> wrote:
>>> You could write:
>>> [x|y <- l, x <- [f(y)], x > 0]
>>> Oh, wait. Thats Haskell. And even in haskell you would write:
>>> [x|x <- map f l, x > 0]
>>> In Python you can write:
>>> [x for x in map(f,l) if x > 0]
>>> In Python 2.x you may want to write:
>>> from itertools import imap
>>> [x for x in imap(f,l) if x > 0]
>>> A more SQL like approach that would fit somewhat with pythons syntax
>>> would
>>> be (as you can see its exactly the same lengths as the above but needs a
>>> new
>>> name):
>>> [f(x) as y for x in l if y > 0]
>>> Because in SQL you can write (IIRC):
>>> select f(x) as y from l where y > 0;
>>> Maybe something like .Nets LINQ would be a nice idea to integrate in
>>> python?
>> Comprehensions and generator expressions already give us most of the
>> LINQ functionality. Add in `list()` and the ability to `.sort()` lists
>> with a `key` argument and you have the entire thing, except for the
>> one corner case being discussed. Unless I've overlooked something...
> Yes: With LINQ its possible to build a query object out of an LINQ
> expression instead of evaluating it eagerly. This is used primarily to
> generate SQL code while still using syntax native to the host language (C#)
> and preserving type safety (ok the later cannot be done in python).

One could probably hack that part together with lambdas, the ast
module, and some black magic though.
And are there any use cases besides SQL?
But point taken.


More information about the Python-ideas mailing list