You have to understand the tradeoff you are making here. As soon as you run exp(var1)
, the return value gets made. It may be dereferenced and garbage collected immediately after the if
check runs, but the variable does exist at that point. So both calls to exp(var1)
create an object. What they do not do, is assign it to a name in your current namespace.
So the tradeoff is to run a (potentially expensive) computation twice, or pollute your namespace with a temporary name. In my opinion, the latter option is foolish to even consier: there are many ways that you can use an effective name.
Prior to python 3.8's assignment expressions, introduced via PEP-572, you had to add an extra line of code:
well_named_result = exp(var1)
if well_named_result:
new_variable = exp2(well_named_result)
In python 3.8 and later, you can use the :=
walrus operator to save even that minor encroachment:
if well_named_result := exp(var1):
new_variable = exp2(well_named_result)
Now if you wanted to call exp2
regardless, but with different parameters depending on the initial trithiness, that you could indeed to without the extra name:
new_variable = exp2(exp(var1) or some_default_value)