conditional for-statement

Mel mwilson at the-wire.com
Mon Aug 24 00:05:44 CEST 2009


seb wrote:

> On Aug 23, 6:18 pm, John Posner <jjpos... at optimum.net> wrote:
[ ... ]
>> How about using a generator expression instead of a list?
>>
>> for i in (x for x in range(10) if x > 5):
>> print i
>>
>> -John
> 
> Indeed, but we could have the same syntax than for generators but
> directly in the for statement as in
> for variable in generator if condition:
>     body
> 
> Is there a special reason for not doing so ? A rejected PEP ?

Well, the Zen of Python does say

There should be one-- and preferably only one --obvious way to do it.

Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer 
Programming_, specifically chapters 11 and 12, about Programming Languages, 
and their design.

The proposal creates an case where one particular pair of syntactic 
constructs can be mooshed together.  OK for them, but everything else 
becomes an exception; what about

while a==c if b != d:

why not

if b != d while a==c:

or

for a in range(7) if os.name == 'posix':


It winds up burdening the programmers with remembering which constructs are 
and which are not mooshable.  Weinberg gave an example: FORTRAN had some 
stringent rules for what expressions were and were not allowed as array 
subscripts.  The result was that many programmers couldn't remember all the 
rules, and often avoided using legal forms, having forgotten they were 
legal.

Maybe the line was already crossed when list comprehensions came into being, 
still, the damage is localized in a particular context: building a list.  It 
isn't out creating wild options in the program control flow at large.

	Mel.





More information about the Python-list mailing list