[Python-Dev] PEP 340: Breaking out.

Paul Moore p.f.moore at gmail.com
Wed May 4 10:57:45 CEST 2005


On 5/3/05, Nicolas Fleury <nidoizo at yahoo.com> wrote:
> We could avoid explaining to a newbie why the following code doesn't
> work if "opening" could be implemented in way that it works.
> 
> for filename in filenames:
>     block opening(filename) as file:
>         if someReason: break

My initial feeling was that this is a fairly major issue, not just
from an education POV, but also because it would be easy to imagine
someone converting

    f = open(name)
    ...
    close(f)

into

    opening(name) as f:
        ...

as part of a maintenance fix (an exception fails to close the file) or
tidy-up (upgrading code to conform to new best practices). But when I
tried to construct a plausible example, I couldn't find a case which
made real-life sense. For example, with Nicolas' original example:

    for name in filenames:
        opening(name) as f:
            if condition: break

I can't think of a reasonable condition which wouldn't involve reading
the file - which either involves an inner loop (and we already can't
break out of two loops, so the third one implied by the opening block
makes things no worse), or needs the whole file reading (which can be
done via f = open(); data = f.read(); f.close() and the opening block
doesn't actually help...)

So I believe the issue is less serious than I supposed at first - it's
certainly a teaching issue, but might not come up often enough in real
life to matter.

Oh, and by the way - I prefer the keywordless form of the block
statement (as used in my examples above). But it may exacerbate the
issue with break unless we have a really strong name for these
constructs ("break exits the innermost enclosing for, while, or um,
one of those things which nearly used the block keyword...") Actually,
maybe referring to them as "block statements", but using no keyword,
is perfectly acceptable. As I write, I'm finding it more and more
natural.

Paul.


More information about the Python-Dev mailing list