Let's say we have the following code:
if re.search(r"b.", "foobar"):
return re.search(r"b.", "foobar").group(0)
This is obviously a redundant call, which can be avoided by assigning the condition to a variable before the if block:
match = re.search(r"b.", "foobar")
if match:
return match.group(0)
However, this means that the condition is always evaluated. In the example above, that makes no difference, but if the match is only used in an elif
block, that's an unnecessary execution.
For example:
match = re.search(r"b.", "foobar")
if somecondition:
return "lorem ipsum"
elif match:
return match.group(0)
If somecondition
is true and we had the redundant version like in the first code block, we would never call re.search
. However, with the variable placed before the if-elif-Block like this, it would be called unnecessarily. And even with the duplicated call, we're instead executing it twice if somecondition
is false.
Unfortunately, depending on the use case, evaluating the condition could be very computationally expensive. With the two variants above, if performance is the goal, a choice can be made depending on the likelyhood of somecondition
evaluating to true. More specifically, if the elif block is called more often than not, declaring the variable before if the if block is more performant (unless Python somehow caches the result of two identical stateless function calls), whereas the alternative is better if the elif block is rarely reached.
Is there a way to avoid this duplication by reusing the variable from the (el)if block?