3 ms·
As a person who reads your code I'd like to know which one you were checking for. If you were checking for None or an empty list, for instance, because there is
by crdoconnor 11y ago
As a person who reads your code I'd like to know which one you were checking for. If you were checking for None or an empty list, for instance, because there is often a non-semantic difference between them.
E.g. one can mean "value not provided" while the other means "there aren't any of that thing" and the behavior you want will often be different depending upon which one it is.
It's this type of subtle difference that often causes obscure bugs.
- StavrosK 11y agoIf I need different behaviour between "value not provided" and "there aren't any of that thing", I would perform both checks (if x is None:/if not x:). The idiomatic way to check for an empty list is "if not mylist", but I still enjoy the fact that I can check for "if this is anything other than a thing I care about, do this" with one check. Not to mention that doing anything else would violate duck typing. You don't care if the thing passed is an empty list, you care if it's falsy. If you had a "reverse()" function that checked for an empty list and raised an exception, you'd get in trouble when someone passed an empty tuple. What you care for is whether the object is iterable or not, not whether it's a list.
- crdoconnor 11y ago>If I need different behaviour between "value not provided" and "there aren't any of that thing", I would perform both checks (if x is None:/if not x:). They will both be true if x is None. What you probably want is actually: if x is None: and if len(x) == 0:
- StavrosK 11y agoI know they'll both be true, the first one will return (or I'll use elif). You definitely want the falsy comparison, the second object may not have len defined.
- icebraining 11y agoYour code is brittle; it'll fail when I pass it a generator expression, and for no good reason.
- crdoconnor 11y agoIf I'm checking the length of what I think is a list and it turned out to be a generator I WANT it to fail.
- kibibu 11y agoPHP does few things right, but it provides an `empty` function for documenting this use case - it will return true for empty strings, null, empty arrays, and unset variables, among others.
- icebraining 11y agoWhy is null "empty"? That seems worse than being implicit - it's misleading.
- kibibu 11y agoBecause there is nothing in it?