24 ms·
How is "dictionary[key] = None" equivalent to dictionary[key] not existing?
by Rygian 4y ago
How is "dictionary[key] = None" equivalent to dictionary[key] not existing?
- masklinn 4y agoIn general it’s not, although for a number of languages (e.g. java, ruby, go) it kinda is. Here the dictionary is supposed to hold Item values, not Optional[Item], so None would be the signal of a missing item. Think Lookup k -> Map k a -> Maybe a Not sure how that came about tho, as the article specifically argues against returning a None for missing entries?
- dontlaugh 4y agoDepends on the language. In Python, dictionary[key] will raise an exception if the key doesn't exist. If there is a value it's returned, even if that value is None.
- quietbritishjim 4y agoThe article never claims that anywhere. That makes it hard to interpret your comment because there are a few places where the article slightly conflates a non-existent key with value == None and maybe you're obliquely referring to one of those, but I'm not sure which one. All of them are OK so long as the dictionary doesn't have having any values equal to None, which it should really spell out but is obviously implied. Actually, most of them even require that none of the values are falsey (e.g. 0, empty list, None, or indeed False). It would actually be possible to work around that but still fundamentally use the same ideas by using a sentinel value: # At file scope, not exposed _not_present_sentinel = object() # Version B def read(self, id_: str) -> Item: result = self.items.get(id_, _not_present_sentinel) if result is _not_present_sentinel: raise ItemNotFound(id_) return result
- Rygian 4y agoThe article starts with a poll showing Versions A), B) and C). Implicit in that poll would be that all three "versions" produce the same behavior. Options A) and B) conflate None with non-existent key: if the key is set and has value None, they will return ItemNotFound. Option C) on the other hand treats them separately and will happily return None (instead of raising exception) when the key exists and its value is None.