Hacker News new | ask | show | jobs
by glxxyz 1795 days ago
As it's error prone, and only saves 1 character, it's not a great shorthand.
1 comments

EDIT2: What I was replying to is no longer there.

It does short circuit, your logic is just purposely fragile. If you reverse the variables it will print Empty, because the and statement evaluates left to right and stops if one of the arguments is falsey.

  print(len(foo) > 0 and foo[0]  or "Empty")
And since len can't give negative numbers the more Pythonic way to do it would be like this. Even though I generally prefer normal if blocks.

  print(len(foo) and foo[0]  or "Empty")

edit: I do agree that you should probably avoid doing this at all, because it is easy to introduce subtle bugs.
My logic wasn't purposely fragile, I missed that the test goes on the left hand size of the 'and', which makes my case that it's error prone ;)