assignment expression peeve
Daniel Dittmar
daniel.dittmar at sap.com
Wed Oct 15 04:55:49 EDT 2003
Paul Rubin wrote:
> OK, I want to scan a file for lines matching a certain regexp. I'd
> like to use an assignment expression, like
>
> for line in file:
> if (g := re.match(pat, line)):
> croggle(g.group(1))
[...]
> It gets annoying when there are 4 different regexps that the line
> might match, and I want to do something different depending on which
> one matches. That's not that uncommon a text scanning situation.
> With assignment expressions, it's a very natural if/elif chain:
[...]
> This kind of regexp matching is a common pattern and I keep wanting
> assignment expressions whenever I code it, and end up crocking up some
> silly workaround.
If this is a common pattern in your code, then write an iterator class that
reads lines from a file and spits out the match object (+ tag, so you know
which regular expression was matched.
So your code becomes:
for match, tag in LineMatcher (...).parseFile (fname):
if tag == tag1:
action1
elif tag == tag2:
action2
cons: you have to invent names for every pattern
pros: patterns are compiled and thus more efficient
Daniel
More information about the Python-list
mailing list