On Mon, 2008-09-15 at 12:37 +1200, Greg Ewing wrote:
Cliff Wells wrote:
factors = for x in range ( 2, n ): if n % x == 0: yield x
Is this construct meant to be a list comprehension or a generator expression? If it's a GC, you just get factors bound to an iterator, not a list of results from that iterator.
First thing, I've recanted reusing "yield" (see below), but your questions still hold in any case. It evaluates to an iterable, I think a generator being the logical choice (although I've been using "[]" to indicate an empty iterable in discussion for brevity).
If it's an LC, then what do you do if you want a dict or tuple comprehension instead?
Did we already grow those? I don't want to debate tuple comprehension (I admit I fail to see the point), but dict comprehensions would be great. To be clear, I'm aiming for as much backwards-compatibility as possible, so I'm in no way suggesting removing comprehensions (although I think they'd become somewhat redundant). In the hypothetical absence of a comprehension feature, I'd probably try to write one like these (I'm slipping "continue" in here as a replacement for yield, which I explain below): x = for i in j: if i: continue i else: continue i**2 # list comp x = dict ( for i in j: continue i, i**2 ) # not a dict comp ;-)
Also, 'yield' already has a meaning that's different from what you seem to want here. Consider:
Yes, that's why I had to retract using the yield keyword in this context. Instead I propose either a new keyword or allowing continue to accept an optional argument causing it to mean "yield expression and continue" rather than just "continue": factors = for x in range ( 2, n ): in n % x == 0: continue x continue without an argument would continue to mean what it does now. This raises some other concerns, but it's an option to be weighed against adding a keyword. In any case, using "yield" is straight out. Regards, Cliff