3 ms·
The alternative here (which would make your example work) is that dictionary lookups return some falsy sentinel value when the key does not exist, just like in
by tomn 4y ago
The alternative here (which would make your example work) is that dictionary lookups return some falsy sentinel value when the key does not exist, just like in javascript. In javascript, this has made a lot of people very angry and been widely regarded as a bad move.
Those values tend to propagate out and make a mess, sneaking into your stored data or causing errors in unexpected places -- fixing this feels like one of the main advantages of using things like typescript, and it's just not an issue in python.
It's not a problem, because the alternative is way worse. It's just a different language design than the one you're used to.
You could argue about whether or not truthiness makes sense as a concept (personally I think not), but the way it's defined in python is quite coherent and useful in practice.
- heavyset_go 4y ago> The alternative here (which would make your example work) is that dictionary lookups return some falsy sentinel value when the key does not exist, just like in javascript. In javascript, this has made a lot of people very angry and been widely regarded as a bad move. You get that behavior by using dict.get(): answers.get("I exist") returns None, which is falsy.
- tomn 4y agoRight, sometimes you want that. I suppose my point was that the definition of truthiness works well with the default, most obvious way of indexing a dictionary, which was the original complaint. Perhaps I was a bit harsh -- that exposes an issue which does trip people up, where they use `if x:` when you mean `if x is not None:`. Saying that, I think it's defensible in the same way. The fact that you can write `if x:` (where x is not a bool) tells you that the language has a concept of truthiness, and so maybe you should have a think about what that actually means.