[Python-3000] Adding sorting to generator comprehension
jcarlson at uci.edu
Mon Apr 24 19:25:49 CEST 2006
Ian Bicking <ianb at colorstudy.com> wrote:
> In another thread ("Brainstorming: Python Metaprogramming") it occurred
> to me that many LINQish things are reasonable enough given the AST and
> generator expressinos. But sorting is hard to do. Sorting also remains
> a place where lambdas are still frequently needed, like:
> sorted(list_of_people, key=lambda p: (p.lname, l.fname))
> We got rid of the lambda-encouraging map and filter, maybe one more?
> (p for p in list_of_people orderby (p.lname, p.fname))
> I have no particular opinion on the keyword, though I assume a keyword
> is required; it may be difficult to find a keyword that people are not
> frequently using (but then this is py3k, so maybe not as big a deal).
> By including this in the generator expression AST introspection makes it
> possible to translate that to a SQL ORDER BY clause; I'm sure other
> out-of-Python query processors (like one of the numeric packages) could
> use this similarly.
> But, putting the AST stuff aside, I also think it is just nice syntax
> for a fairly common case, and a nice compliment for comprehensions.
One of the features of generator expressions which makes it desireable
instead of list comprehensions is that generator expressions may use
less memory *now*, and may be able to start returning results *now*.
Using (<genexp> orderby ...) as a replacement for sorted((genexp), key=...)
is a bit misleading because while the original generator expression
could have been space and time efficient, the orderby version certainly may
More information about the Python-3000