0

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?

PixelMaster
  • 895
  • 10
  • 28
  • 3
    Depends on what Python version you use. This very use-case is the classic example for the (now not so much) new [walrus operator](https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions) – Tomerikoo Jan 24 '23 at 12:52
  • 1
    I think you can use the walrus operator `:=` introduced from python 3.8 onwards – Ashyam Jan 24 '23 at 12:52
  • 2
    Examples given here: https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions – Chris Jan 24 '23 at 12:54
  • 1
    @Tomerikoo not the latest version, but luckily a new enough version (3.9). Thanks for the help, this is exactly what I was looking for! – PixelMaster Jan 24 '23 at 21:28

0 Answers0