On 29/01/13 21:44, Nick Coghlan wrote:
On Tue, Jan 29, 2013 at 11:30 AM, Steven D'Aprano
wrote: Why would it translate that way? That would be a silly decision to make. Python can decide on the semantics of a while clause in a comprehension in whatever way makes the most sense, not necessarily according to some mechanical, nonsensical translation.
Terry is correct: comprehensions are deliberately designed to have the exact same looping semantics as the equivalent statements flattened out into a single line, with the innermost expression lifted out of the loop body and placed in front.
You have inadvertently supported the point I am trying to make: what is *deliberately designed* by people one way can be deliberately designed another way instead. List comps have the form, and limitations, they have because of people's decisions. People could decide differently. A while clause in a comprehension can map to the same statement form as currently used. Just because the parser sees "while" inside a comprehension doesn't mean that the underlying implementation has to literally insert a while loop inside a for-loop. Terry is right about one thing: that would lead to an entirely pointless infinite loop. Where Terry gets it wrong is to suppose that the only *conceivable* way to handle syntax that looks like [x for x in seq while condition] is to insert a while loop inside a for loop. But "while" is just a convenient keyword that looks good, is readable, and has a natural interpretation as executable pseudo-code. We could invent a new keyword if we wished, say "jabberwock", and treat "jabberwock cond" inside a comprehension as equivalent to "if cond else break": (x, y for x in a jabberwock x for y in b jabberwock y) for x in a: if x: for y in b: if y: yield (x, y) else: break else: break If you, as a core developer, tell me that in practice this would be exceedingly hard for the CPython implementation to do, I can only trust your opinion since I am not qualified to argue. But since you've already allowed that permitting "if cond else break" in comprehensions would be possible, I find it rather difficult to believe that spelling it "jabberwock cond" is not.
The only remotely plausible proposal I've seen in this thread is the "else break" on the filter conditions,
Which just begs for confusion and misunderstanding. Just wait until people start asking why they can't write "else some_expression", and we have to explain that inside a comprehension, the only thing allowed to follow "else" is "break". -- Steven