[Python-ideas] Nudging beginners towards a more accurate mental model for loop else clauses

Nick Coghlan ncoghlan at gmail.com
Fri Jun 8 13:53:03 CEST 2012


On Fri, Jun 8, 2012 at 7:44 PM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> I think a better scheme would be to have more meaningful keywords or
> keyword-combinations, e.g.
>
> for x in iterable:
>    # do stuff
> ifempty:  #  or perhaps ifnoiter: (also applicable to while loops)
>    # do stuff
> #ifbreak:
>    # do stuff
> #ifnobreak:
>    # do stuff
>
> which would give all the flexibility while making it reasonably clear what
> was happening.

The way to be clear would actually be to drop the feature altogether
(as Guido has noted in the past). Then TOOWTDI becomes:

    x = _no_data = object()
    result = _not_found = object()
    for x in iterable:
        if acceptable(x):
            result = x
            break
    if x is _no_data:
        # No data!
    if result is _not_found:
        # Nothing interesting!
    # Found a result, process it

That's never going to happen in Python though, due to backwards
compatibility requirements.

FWIW, I wrote an essay summarising some of the thoughts presented in
these threads:
http://readthedocs.org/docs/ncoghlan_devs-python-notes/en/latest/python_concepts/break_else.html

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list