1

I often have to write lines such as:

if exp(var1):
   new_variable = exp2(exp(var1))

As you can see, this statement evaluates exp twice - one for the condition and then within the body of the if statement. Is there a neat pythonic way to write this so that exp is evaluated only once?

I know that I can write:

temp_variable = exp(var1)
if temp_variable:
     new_variable = exp2(temp_variable)

but this introduces a new variable. My question specifically is if there is a solution that's more elegant than this one.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
vineeth venugopal
  • 1,064
  • 1
  • 9
  • 17
  • 3
    I don't know of a way that doesn't introduce a new variable. `if temp := exp(var1): exp2(temp)` can be used to inline the assignment though. – Carcigenicate Jul 23 '21 at 21:05
  • 3
    There is nothing wrong with introducing another variable. In fact, one purpose of having variables is to store intermediate results for further reuse. – DYZ Jul 23 '21 at 21:13
  • 2
    @DYZ. Not to mention that just because you didn't name a variable, doesn't mean it wasn't created. – Mad Physicist Jul 23 '21 at 21:22
  • @mkrieger1. I think I've made the answer sufficiently different to justify this not being a duplicate. – Mad Physicist Jul 24 '21 at 03:51

1 Answers1

2

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)
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264