I don’t think it’s trivial. I don’t want to have to sprinkle a redundant conditional around my code if I’m writing code like that often.
This is slightly odd, but you can do this with an iterator:
import re
def rematch(pattern, inp):
matcher = re.compile(pattern)
matches = matcher.match(inp)
if matches:
yield matches
if __name__ == '__main__':
for m in rematch("(\d+)g", "123g"):
print(m.group(1))
The odd thing is that it’s using an iterator for something that isn’t iterating–it’s closer to a conditional, and at first glance it might look like it’s going to yield multiple results for each match.
It does seem odd that a context manager can’t cause its managed function to be skipped entirely; while that’s not explicitly one of the use cases of “with”, it seems like a natural extension.