Earlier quoted context omitted.
Coming from Perl, I used to want this badly, but then I thought that there's absolutely nothing wrong with m = re.match(...) if m is not None: pass Now, I wonder what you meant saying that single-line version is less error-prone, because I don't think so. I believe they're exactly the same in this regard, except for a bizarre case when someone would bastardize the code by putting some irrelevant lines between the ass…
Think about if you match multiple patterns: for line in f: if (m:= pat1.search(line)) is not None: ... do stuff .. elif (m:= pat2.search(line)) is not None: ... do other stuff .. elif (m:= pat3.search(line)) is not None: ... do something else .. In older Python that's: for line in f: m = pat1.search(line) if m is not None: ... do stuff .. else: m = pat2.search(line) if m is not None: ... do other stuff .. else: m = p…
LINE_ACTIONS = (
(re.compile("pattern 1"), do_stuff),
(re.compile("pattern 2"), do_other_stuff),
(re.compile("pattern 3"), do_something_else),
)
...
for pattern, action in LINE_ACTIONS:
m = pattern.search(line)
if m is not None:
action(m)
break
Or even use a method registry pattern that would auto-populate LINE_ACTIONS by just declaring the fuctions: @action("pattern 1")
def do_stuff(m):
...
Alternatively, I might just break the processing into a function: def _process(line):
m = pat1.search(line)
if m is not None:
... do stuff ...
return
m = pat2.search(line)
if m is not None:
... do stuff ...
return
m = pat3.search(line)
if m is not None:
... do stuff ...
return
_process(line)
Of course, this depends on the purpose. Could be completely inadequate in some situations.