How to do this in Python...

Martin Maney maney at pobox.com
Mon Jan 27 23:46:53 EST 2003


Chad Netzer <cnetzer at mail.arc.nasa.gov> wrote:
> Here is is again (excerpted):

Yes, I've seen this before.  As presented I don't see how it fits the
use case at all: how do you select the action to take that depends on
which pattern matches?  If you extend it to include that, it only gets
heavier, and in every example I've seen it breaks the simple and
obvious relation between the pattern and the action that's associated
with it.

The simple code-pattern (pseudo code to avoid controversial syntax)

if pattern1 matches target:
    process results as type 1
elif pattern2 matches target:
    process results as type 2
...

concisely but cleanly captures the key design elements.  Most of the
proposed work-arounds sacrifice one or more of its virtues:

  1) relation of pattern to the action it is associated with

  2) visibility of the order in which patterns are tested

The solutions that equally clearly expose the bones of the design have
other issues.  I am increasingly convinced that someone needs to write
a letter that can be published under the title "Recipie 1.9 Considered
Harmful" - its convenience comes at the cost of invisible global state
that makes it much too fragile for use in anything but true use-once
code - and who ever really throws the use-once code away after it's
been used?  Not me!

On the other hand, the above does not make it so clear as it might be
that every test is exactly the same aside from the pattern being tried. 
Several of the alternate solutions have the advantage of making that
very explicit, but that can also make them less satisfying a fit when
you do have one or more cases that require a different sort of test. 
No one pattern is best for all uses.

As I said, for this particular case I have been pretty happy with the
lightweight class wrapper around [compiled] regexp approach... but in
the body of code where I've needed it up to now, I was already
sacrificing virtue #1 by pre-compiling the patterns - makes sense when
you expect to execute the selection hundreds to thousands of times in
every run, or so I told myself.  Besides, I gave the compiled
pattern/objects meaningful names.  <wink>

So it's not that I'm not willing to make trade offs; I just dislike
being forced to do so for what seems to be little more than a
prejudice... except maybe when the prejudice is my own wild guess about
what's worth optimizing in advance.  :-)





More information about the Python-list mailing list