PEP: statements in control structures (Re: Conditional Expressions don't solve the problem)

Andrew Dalke dalke at dalkescientific.com
Thu Oct 18 23:07:24 EDT 2001


Huaiyu Zhu:
>But then I was reminded of the examples I collected by searching for break
>statements in the source distribution.  Most usages are similar to
>
>./Demo/pdist/makechangelog.py:

(final version)
>    while file = getnextfile(f); file:
>        revs = []
>        while rev = getnextrev(f, file); rev:
>            revs.append(rev)
>        allrevs += revs


And in that case (elsewhere in the thread) I showed that it
was better rewritten using an iterator/generator style.  The
most succinct version is

for file in getnextfile(f):
  allrevs.extend(getnextrev(f, file))

Where getnextfile and getnextrev need to be rewritten
as generators.

That's because everything of the proposed form

  while x = f(a); x:

can be written as

  for x in generator_f(x):

and the creation of a generator is, in 2.2, as simple as

  iter(f, None)

or, if f takes parameters, through the use of yield.

I love generators and iterators.  :)

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list