4 ms·
Obviously, any falsey value triggers the "idiomatic" contains_zero function: [1, False, 3] [1, '', 3] [1, None, 3] [1, [], 3] This seems like
by freyr 9y ago
Obviously, any falsey value triggers the "idiomatic" contains_zero function:
[1, False, 3]
[1, '', 3]
[1, None, 3]
[1, [], 3]
This seems like it could only make bugs harder to track down, yet this is often touted as the Pythonic way. What's the benefit of this approach?
- empthought 9y agoThe original implementation of `contains_zero` in the blog post is not idiomatic. (It's also incorrect, as you point out.) The idiomatic implementation of `contains_zero` is the second one given, `0 in container`. Just because someone claims something is idiomatic in a book doesn't mean they are correct about it being idiomatic.
- freyr 9y agoYou're right. PEP8 says: > beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context! This should apply to the contains_zero function as well. It seems a little murky when PEP8 recommends checking whether a sequence type is empty, Yes: if not seq: if seq: No: if len(seq): if not len(seq): if seq were accidentally set to False or 0. But I guess that would be revealed as soon as you start treating seq like a sequence.