On 6/18/05, D H <[EMAIL PROTECTED]> wrote:
> I would hardly call using a
> dictionary as a switch statement, the "equivalent".  The fact that
> people use a dictionary as a conditional is a python wart.

Not at all. A case statement is nothing more than a literal mapping of
constant values to the execution of code blocks; a dictionary is a
(not necessarily literal) mapping of hashable (not just constant)
values to other values. A dictionary is a very close match for the
operation of a case statement.

In the common (in my experience) instance where the case statement is
like (using C notation):

switch(x) {
    case 1: y = foo; break;
    case 2: y = bar; break;
    case 3: y = baz; break;
    default: y = qux;
}

In this case the dictionary is obviously a better and clearer choice.
I've generally found for other circumstances where I've used switch
statements that the code ends up more readable if it's reorganised so
that the switch statements are all of the form above, or are
eliminated entirely--so I don't miss a switch/case statement in
Python.

And, just because we can, the most direct equivalent (in terms of
written code) of a switch/case statement in Python is:

exec {
    1:  "y = foo",
    2:  "y = bar",
    3:  "y = baz"
}.get(x,"y = qux")

But I didn't say it was nice...
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to