Without knowing what else you might want to return there are a few options.
-
You could just return the result of the function,
Noneor not:return slow_function()In this, you rely on the caller knowing what to do with the
Nonevalue, and really just shift where your logic will be. -
If you have a default value to return instead of None, you can do this:
return slow_function() or defaultIn this above, if
slow_functionisNone(which is “falsy”) it will return the latter value, otherwise, ifslow_functionreturns a “truthy” value it will return that. Beware, ifslow_functioncan return other “falsy” values, likeFalse,[]or 0, those will be ignored. -
Alternatively, sometimes what you have is perfectly valid code. You want to compare against a value, and if it is value, return it. The code you have is obvious in what it does, and sometimes that is more important than the “cleverness” of the code.
As per the comments, if your code must continue running if the value is None then the most obvious way to do it is store it as a temporary value. But, thats not a bad thing, as it reads cleanly.
- Compute a value and store it as the result
- If there is a valid result, return it.
- Otherwise, keep doing things to get a better result.
Better is usually very subjective, and I can’t see any obvious ways to improve this from a computation perspective, and as written it is very human readable which is a clear advantage. Other solutions may be shorter or cleverer, but human readability is often an over looked advantage for code.