4 ms·
I've worked in a lot of different languages, from ones that work the way I prefer all the way to Python-style languages where anything is a predicate and there
by mikeash 7y ago
I've worked in a lot of different languages, from ones that work the way I prefer all the way to Python-style languages where anything is a predicate and there are a bunch of semi-arbitrary rules about what qualifies as "false." This isn't a lack of familiarity talking.
Regarding your examples, having an optional sequence is probably not the correct move anyway. Is there actually a semantic difference between no sequence and an empty sequence? If not, the variable should be non-optional. If so, then glossing over those differences by writing `if x` to implicitly check both conditions is unclear. Not sure what you're referring to with get() in a dictionary.
I understand that good Python style is considered to be one where you take advantage of the language's notion of truthiness, but I disagree with its whole approach.
- raverbashing 7y ago> Is there actually a semantic difference between no sequence and an empty sequence? It really depends on your function, but you might want to have the function behave differently if given an empty list rather than no list. One very common case for doing that is when you want to facilitate unit testing of a function. > Not sure what you're referring to with get() in a dictionary. A very common case, in which you don't care if the element is not present or it is a "False" element.
- mikeash 7y agoBehaving differently on an empty list than on no list is a huge smell. That's really weird and unexpected behavior. Doing it for testing is even weirder. If you're fetching an element from a dictionary and want not-present to be the same as some false value, fetch with a default value (in Python, pass a second parameter to get()) that you want to see when there's nothing present. Or just extract the value and check for nil or empty separately, nothing wrong with being explicit.
- jhayward 7y agoThere are Python idioms for exactness, and idioms for truthiness. When in a situation where it's possibly ambiguous to test truthiness 'if x is None:' or 'if x is True': is completely unambiguous. Most code doesn't need that and the truthiness nature of various data types is helpful in writing clear code.