for what are for/while else clauses

Magnus Lyck? magnus at thinkware.se
Thu Nov 27 18:19:28 EST 2003


aahz at pythoncraft.com (Aahz) wrote in message news:<bpoce2$de8$1 at panix2.panix.com>...
> In article <258fd9b8.0311220938.3210484c at posting.google.com>,
> Magnus Lyck? <magnus at thinkware.se> wrote:
> >
> >On the other hand, I only think it's in the case of a break
> >in block that...
> >
> >while condition:
> >    block
> >else:
> >    print "Loop finished"
> >
> >...will behave differently than...
> >
> >while condition:
> >    block
> >print "Loop finished"
> >
> >So, unless you use a break in the block, the else statement is just
> >noise: an extra line of code and additional whitespace for the
> >following statement(s).
> 
> While technically correct, I don't think you could claim that it's "just
> noise" in this example:
> 
>         try:
>             for ORlist in includes:
>                 try:
>                     for filter in ORlist:
>                         for field in curr_fields:
>                             for item in record[field]:
>                                 if match(item, filter):
>                                     raise Found
>                     else:
>                         raise NotFound
>                 except Found:
>                     continue
>         except NotFound:
>             continue
>         else:
>             result.append(record)

First of all, I'm not sure it's a good idea to use
exceptions like a poor (rich?) man's GOTO like this. :)

If you persist, I'm not so sure your code is clearer than:

        try:
            for ORlist in includes:
                try:
                    for filter in ORlist:
                        for field in curr_fields:
                            for item in record[field]:
                                if match(item, filter):
                                    raise Found
                    raise NotFound
                except Found:
                    continue
        except NotFound:
            continue
        else:
            result.append(record)

With the else clause on the for loop, just after the if
statement, you are bound to confuse people. I would guess
that most people who casually looked at that code would
think that you had made an indentation mistake. Some would
probably "correct" it.




More information about the Python-list mailing list