3 ms·
Most of the time when I see python ternary in the wild, it makes the code less readable, not more. Why not just define something like this if you want oneliners
by apocolyps6 5y ago
Most of the time when I see python ternary in the wild, it makes the code less readable, not more. Why not just define something like this if you want oneliners?
def if_then_else(cond, true_case, false_case):
if cond:
return true_case
return false_case
x = if_then_else(condition, 4, 5)
- shultays 5y agoConsider this: x = if_then_else(condition, calc1(), calc2()) Here it will call both calc1 and calc2 even though it will ignore one depending on condition. They might be expensive operations, or might have side effects that you don't want. The original code does not evaluate the part that is not used
- apocolyps6 5y agoIn that case I'd stick an `if callable` check in if_then_else. But really... ternary is a nice way to draw attention away from simple pieces of code. If you have anything complicated (like functions with side effects) spend the extra 3-4 lines to make it readable