Live data from Hacker News

New Ways to Be Told That Your Python Code Is Bad

nickdrozd.github.io

261–262 of 262 posts

Re: New Ways to Be Told That Your Python Code Is Bad

#261
post #230

Earlier quoted context omitted.

Can you give me an example where the two return different values?

When condition() is truthy, the first evaluates to True and the second evaluates to [] Try it out. https://ideone.com/GciAs8

So the problem is not in condition() but in the the other statement/expression. Similarly,

    True and False or 5
returns 5 rather than False.

Re: New Ways to Be Told That Your Python Code Is Bad

#262
post #71

Earlier quoted context omitted.

Also worth remembering that a perl statement can be converted into an expression with a do block, so you can write my $x = do { if (foo()) { 4 } else { 5 } }; (and yes, I know, that example would look fine as a ternary - but this is meant to illustrate the syntax possibility, not where I'd specifically use it - and once the logic within one of the two conditional branches gets more complicated, switching to do+if+els…

What the... ? Why is that worth remembering? Just reading that code makes me feel dirty, let alone deploying it! ;-)

Sometimes the logic in at least one of the arms of the if/else is sufficiently complicated to make it worthwhile (e.g. cases where you find yourself needing a 'do' block inside a ternary).

Also doing that with if/elsif/elsif/else is often far more readable than nested/chained ternaries.

Post reply on HN