How to write the expression shorter:
return '%.0f' % float_var if float_var else float_var
or
if float_var:
return formatted_string
else:
return None
Thanks!
The expression <value> if <condition> else <other_value>
is pretty idiomatic already -- certainly more so than the other example, and is probably preferred whenever <value>
is simple. This is Python's ternary operator, so if you were looking for something like <condition> ? <value> : <other_value>
, that doesn't exist.
If computing <value>
or <other_value>
takes a few steps, use the longer if: ... else: ...
alternative.
I would use brackets to make the expression more readable:
return ('%.0f' % float_var) if float_var else float_var
When I first saw it I read it as
return '%.0f' % (float_var if float_var else float_var)
which would be silly. I had to try it out to make sure which way it worked.
BTW Your first example not equivalent to your second example
if float_var:
return formatted_string
else:
return None
This will always return either a formatted string or None. Your first example if you pass in anything that evaluates to False (False, 0, 0.0, "", [] etc) will return that unchanged, so your return type could be string, boolean, list, int, float etc. This is probably not what you want, especially if 0.0 is a legitimate value for float_var. I would change your code to:
return ('%.0f' % float_var) if isinstance(float_var, float) else None
alternatively:
try:
return "%.0f" % float_var
except TypeError:
return None
which will work for other integers (and longs) by converting them to float.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With