Ethan Furman writes:
On 03/05/2014 07:42 AM, Paul Moore wrote:
On 5 March 2014 15:08, Yann Kaiser
wrote: Let me show you an actual zero:
if event.num_attendants: prepare_cake() else: cancel_event()
I'm sorry, are you really trying to say that the above code is better than
if event.num_attendants != 0: prepare_cake() else: cancel_event()
?
Yes. This is Python. blah blah blah != 0 is unnecessary boiler-plate.
I wouldn't call that *better*, just a different style. I agree I prefer "if blah.count:" to "if blah.count != 0:", but I might very well write "if blah.count > 0:". I don't see anything "wrong" with using an explicit comparison, but I don't have a problem reading the abbreviated style in this situation.[1] Personally I would *always* use the "implied boolean" style for emptiness tests (I'm an old Lisper), but I might very well use explicit comparisons against zero. For example, I would be likely to write the party example with a reversed test (to keep 'if' and 'else' close together): if event.num_attendants == 0: # nobody's coming cancel_event() else: # several-pages-long suite of preparations prepare_cake() and I think that looks better than if not event.num_attendants: # it's a count, not a boolean # etc But actually I'd probably design the event class differently, and write it as: if not event.list_of_attendants: # attendance list is empty # etc or perhaps if event.list_of_attendants: # attendance list is non-empty # reverse the suites (depending on the phase of the moon and whether the trout are running in Esopus Creek to choose between the last two :-). Footnotes: [1] I do have a real issue with the "if x:" to test for a sentinel meaning "uninitialized" that happens to evaluate to false. There's objectively a probability that it would pass an error that would be caught if the "is None" form were used, but that probability is admittedly low. Tastes may differ regarding "importance" here.