1

Is there a way to do the following in a one-liner:

x = heavy_computation() if heavy_computation() > 0 else None

without heavy_computation() being called twice? Of course, one could do:

val = heavy_computation()
x = val if val > 0 else None

but I was wondering if there is a more pythonic way to achieve this in one line. This might be useful for heavy computations but also for better code readability.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Federico Taschin
  • 2,027
  • 3
  • 15
  • 28

1 Answers1

1

You could consider using the walrus operator (PEP 572):

x = val if (val := heavy_computation()) > 0 else None

Note that it requires a recent Python version (at least 3.8).

I'm not sure if it's much more readable though.

jfschaefer
  • 293
  • 1
  • 8