News for hackers. Stuff that matters.
Re:New Ways to Be Told That Your Python Code Is Bad by l0b0 on Thursday September 02, 2021 @09:12PM (#28399389)
Sure, once you cherry-pick the most trivial imaginable example ternary expressions are easy enough to read. First counter-example which came to mind:

  print("yes") if random.choice([True, False]) else print("no")
Does this do the right thing? I was pleasantly surprised to find that this is indeed lazily evaluated, but that's not at all intuitive: first because `print("yes")` comes before the conditional (note that the Lisp example had the conditional first), and second because not all popular languages work like that.

There are lots of examples where ternary makes things obviously harder to read, such as when at least two of the three expressions are non-trivial. Which one would you rather read?

  if some_complex_condition(using, four, different, parameters):
      do_a_thing(now, using, five, different, parameters)
  else:
      do_another_thing(with, three, parameters)
or

  do_a_thing(now, using, five, different, parameters) if some_complex_condition(using, four, different, parameters) else do_another_thing(having, three, parameters)
(or

  do_a_thing(now, using, five, different, parameters) if some_complex_condition(
      using, four, different, parameters
  ) else do_another_thing(having, three, parameters)
after Black.)
Re:New Ways to Be Told That Your Python Code Is Bad by detaro on Thursday September 02, 2021 @09:23PM (#28399462)
Neither of your examples qualify for the lint rule that's about cases that assign to the same variable, so I'm not sure why you accuse the author of "cherry-picking"?
Re:New Ways to Be Told That Your Python Code Is Bad by l0b0 on Thursday September 02, 2021 @10:44PM (#28399882)
I didn't realize this was only for assignments, but the same applies if you prepend `x =` before the relevant lines.
Re:New Ways to Be Told That Your Python Code Is Bad by nirs on Friday September 03, 2021 @02:36AM (#28401077)
Theses are good examples for not using ternary expressions. The code looks wrong even if it is correct, and it is hard to follow.

There is a very simple rule avoiding most of these issues - if the ternary expression does not fit in one line, use if/else.

Re:New Ways to Be Told That Your Python Code Is Bad by balthasar on Thursday September 02, 2021 @10:01PM (#28399650)
I would write it like this. Seems fine to me

  do_a_thing(now, using, five, different, parameters
      ) if some_complex_condition(using, four, different, parameters
      ) else do_another_thing(having, three, parameters)