for: else: - any practical uses for the else clause?

Carl Banks pavlovevidence at gmail.com
Sat Sep 30 12:39:15 EDT 2006


metaperl.etc at gmail.com wrote:
> I'm wondering if anyone has ever found a practical use for the else
> branch?

Say you have code that looks like this:

if command.startswith("set"):
    do_set_action(command)
elif command.startswith("input"):
    do_input_action(command)
elif command.startswith("print"):
    do_print_action()
else:
    do_general_action()

Now, during refactoring, we note that there's a lot of similarity in
all those if clauses that we can exploit to simplify the code.  Let's
ignore the final else clause for now, since it's not similar to the if
and elif clauses (it has no test).  We define a mapping of prefixes to
actions, and rewrite the if...elif as a for loop:

command_map = (
    ("set",do_set_action),
    ("input",do_input_action),
    ("print",do_print_action)
)

for keyword,action in command_map:
    if command.startswith(keyword):
        action(command)
        break

Ok, this works great.  Now let's come back to that else clause: how do
we translate default case to the for loop?  Well, I guess we could set
some sort of flag indicating we got a match....  But wait!  We don''t
have to!  We can just leave the else clause there as-is, and it'll
work.  The for loop here is quite literally a drop-in replacement for
the if...elif...elif, even going so far as to allow the same else
clause.

for keyword,action in command_list:
    if command.startswith(keyword):
        action(command)
        break
else:
    do_general_action()


Moral of the story: there are two ways to do a linear search (or linear
sequence of tests): either an unrolled sequence of if...elif...elif
clauses, or a rolled up for loop with a break.  Either way you do it,
you can tack on an else clause for when you don't find anything.


Carl Banks




More information about the Python-list mailing list