How to do this in Python...

Alex Martelli aleax at aleax.it
Tue Jan 28 05:00:55 EST 2003


Cliff Wells wrote:
   ...
> 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"

Weird to use filter AND list comprehension when just the latter
would suffice,,,:

if [match for match in [re.search(pattern1,target)] if match]:

etc.  The if clause in the list comprehension is useful here.


Personally, I consider this idiom a (slight) _abuse_ of list
comprehensions -- specifically, of the "implementation detail"
that any identifier that gets bound in the for clause of a
list comprehension gets bound in the SURROUNDING scope, i.e.,
a list comprehension does not define a new nested scope.

I guess that, if the idiom becomes a popular replacement for
the missing assign-and-test, all future releases of Python
will be practically constrained to let list comprehensions
always "pollute" the surrounding scope in this way.  But this
does not strike me, personally, as a very nice prospect anyway.


Alex





More information about the Python-list mailing list