conditional for-statement

seb sdementen at gmail.com
Tue Aug 25 13:30:15 EDT 2009


On Aug 24, 12:05 am, Mel <mwil... at the-wire.com> wrote:
> 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:
>

what would be the unambiguous meaning of any of these forms ?
they could be interesting but I do not understand them (yet!).


> 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.

indeed, the language features should stay as orthogonal as possible
(at least as a general rule)

>
> 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.
>

indeed and it proved to be very useful & successful.
one cannot recommend to mix all features together as a general rule
but using common sense and practice, we can have some exceptions that
are definitely worth.

>         Mel.- Hide quoted text -
>
> - Show quoted text -




More information about the Python-list mailing list