0

I'm assigning many properties to a dictionary, like this:

dict = {
    "prop1": round(myfunc1(), 2),
    "prop2": round(myfunc2(), 2),
}

myfunc() returns either None or a float number.

I need to do this:

result = myfunc()
if result is not None:
    result = round(result, 2)

But in one line.

The reason a normal Python one liner would not be ok is that myfunc() is a long and resource intensive function, and I definitely don't want to call it twice or implement any lazy loading inside it. This would not be ok:

result = round(myfunc(), 2) if myfunc() is not None else None

Is this doable?

Saturnix
  • 10,130
  • 17
  • 64
  • 120

2 Answers2

3

Ok... this is pretty horrible, and I'm not proud, but if it's gotta be one line:

result = next(None if v is None else round(v, 2) for v in (my_func(),))

Is it worth avoiding two lines over? Only you can know.

Jon Betts
  • 3,053
  • 1
  • 14
  • 12
3

Python 3.8 (applying Walrus Operator)

result = round(f, 2) if f := myfunc() is not None else None