Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python idiom for '... if ... else ...' expression

Tags:

python

idioms

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!

like image 268
rukeba Avatar asked Mar 27 '10 14:03

rukeba


2 Answers

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.

like image 75
John Feminella Avatar answered Sep 22 '22 23:09

John Feminella


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.

like image 43
Dave Kirby Avatar answered Sep 26 '22 23:09

Dave Kirby