2.6 Saving intermediate results with the := ”walrus” operator
Sometimes we’ll have a complex condition where we want to preserve an expensive intermediate result for later use. Imagine a condition that involves a complex calculation; the cost of computing is high measured in time, input-output operations, memory resources, or all three.
An example includes doing repetitive searches using the Regular Expression (re) package. A match() method can do quite a bit of computation before returning either a Match object or a None object to show the pattern wasn’t found. Once this computation is completed, we may have several uses for the result, and we emphatically do not want to perform the computation again. Often, the initial use is the simple check to see if the result is a Match object or None.
This is an example where it can be helpful to assign a name to the value of an expression and also use the expression in an if statement. We...