3

The standard use of the ternary operator is, i.e.:

a = 1 if some_condition else 2

Just today, I realized something like this is perfectly legal:

do_something() if some_condition else do_something_else()

For example:

print(1) if a == 1 else print(2)

instead of:

if a == 1:
    print(1)
else:
    print(2)

In my opinion, this is more compact, readable and prettier. I see that it would be harder to get return values from this type of expression (perhaps the way would be to wrap everything in parentheses). What do you think?

P.S. I know it's not typical Q&A content, but I have never even seen this use of the ternary operator mentioned, and I think it clearly improves some aspects of Python coding.

krsnik93
  • 186
  • 1
  • 11
  • 2
    I won't go on my rant, but if you look up carrying out side effects via ternarys, you'll see many examples of why it isn't great practice. Python's ternary is, Imo, more readable than the `? :` variant, but it's still not proper. – Carcigenicate Mar 23 '18 at 13:28
  • 3
    I think it just as clearly doesn't. This is the very definition of a primarily opinion-based answer. – chepner Mar 23 '18 at 13:28

1 Answers1

5

using ternary operator just for side-effects pretty confusing. The expression is supposed to return something (reminds me of Is it Pythonic to use list comprehensions for just side effects?: answer is no)

You could rewrite:

print(1) if a == 1 else print(2)

like:

print(1 if a == 1 else 2)

or rewrite:

do_something() if some_condition else do_something_else()

to:

(do_something if some_condition else do_something_else)()

so the ternary expression returns something that is used by a side-effect expression.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 2
    The issue is, IMHO, that it is too easy to confuse with `print(1); if a == 1 print(2)`, without providing much benefit. – kutschkem Mar 23 '18 at 13:39