Where is CASE?????
duncan at rcp.co.uk
Tue Feb 20 16:00:48 CET 2001
"Chris Richard Adams" <chrisa at ASPATECH.COM.BR> wrote in
<mailman.982674921.12321.python-list at python.org>:
>Someone please tell me why I cannot find a CASE statement in the Python
>There is a CASE isn't there???
While there are undoubtedly occasions where a CASE statement would be
useful, they are actually much rarer in Python than you might expect. A
large proportion of the instances where you might use CASE can be written
better as a dictionary or an attribute lookup.
For example in most languages if you were to try to handle errors from
opening a web URL, you might reasonably expect to find a case statement
switching on the different error codes you could receive. If you look at the
urllib module you will see that the Pythonic way to do this is to have class
methods with names such as http_error_401, http_error_301, and
http_error_default. When an error code is returned, the appropriate method
is called (or the default method if there is no better match) by using
getattr to look up the method by name. This technique allows the end user to
add their own handler for any error number, even those the original class
knows nothing about.
Another common use for CASE in some languages is when you have created a
structure and put a type field in it. You want to process the object
according to the type field. In any object oriented language (not just
Python), this situation is better handled by including a method in the
object that does the appropriate action for the object's type.
If you post a message outlining the situation where you think you need a
CASE statement you might get suggestions of better (or just different) ways
to solve your particular problem.
More information about the Python-list