How to do this in Python...

Cliff Wells clifford.wells at attbi.com
Tue Jan 28 02:08:37 EST 2003


On Mon, 2003-01-27 at 20:46, Martin Maney wrote:

> 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:


Well, if conciseness is the goal, I'm shocked that no one has suggested
the obvious and practically idiomatic:


if filter(None, [match for match in [re.search(pattern1, target)]]):
    print "1", match.string
elif filter(None, [match for match in [re.search(pattern2, target)]]):
    print "2", match.string
else:
    print "no match"


And to think some people wanted to remove the functional tools in favor
of list comps when they are both equally readable, especially when used
in tandem.  Plus I think Tim Peters mentioned liking this sort of thing.


-- 
Cliff Wells <clifford.wells at attbi.com>






More information about the Python-list mailing list