[Python-Dev] Re: switch statement

Jim Jewett jimjjewett at gmail.com
Fri Apr 22 17:06:16 CEST 2005


Michael Chermside wrote:

> Now the pattern matching is more interesting, but again, I'd need to
> see a proposed syntax for Python before I could begin to consider it.
> If I understand it properly, pattern matching in Haskell relies
> primarily on Haskell's excellent typing system, which is absent in
> Python.

Why not just use classes?  With either mixins or new-style classes,
it is quite reasonable to use many small classes for fine distinctions.

Change 
    if predicate1(obj):
        action1(obj)
    elif predicate2(obj):
        action2(obj)
    ...
    else:
        default(obj)

into either

    try:
        obj.action(locals())
    except AttributeError:
        default(obj, locals())

or

    if hasattr(obj, "action"):
        obj.action(locals())
    else:
        <default>

And then define an action method (perhaps through inheritance
from a mixin) for any object that should not take the default path.  
The object's own methods will have access to any variables used 
in the match and locals will have access to the current scope.  If
you have at least one class per "switch", you have a switch statement.

The down sides are that 

(1)  Your domain objects will have to conform to a least a weak OO 
model (or take the default path)

(2)  Logic that should be together will be split up.  Either classes will 
be modified externally, or the "switch statement" logic will be broken 
up between different classes.  If single-method mixins are used to 
keep the logic close, then real objects will have to pick an ancestor 
for what may seem like arbitrary reasons.

These objections apply to any matching system based on types; the 
difference is that other languages have often already paid the price.
For Python it is an incremental cost incurred by the match system.

-jJ


More information about the Python-Dev mailing list