On a dict returning None
Long time ago a thought came, why does a python dict throw exception, can't it just return a None if there is no key with supplied name.
Well now I understand the point of it, which is very obvious - if a dict has a key "foo" and the programmer has stored None into it, how would one distinguish a non-existant key and the one with None stored into it.
So here is the desired bad extension of dict for the Community Centric Python(CCP) Engineer:
class NoneDict(dict):
def __getitem__(self,key):
try:
return self.get(key)
except:
return None
l = NoneDict()
l[1] = "Foo"
l["a"] = "Bar"
print l[1], l["a"] # gives out the values
print l[42] # gives out None

4 Comments:
This is a standard behavior across most of the frameworks or modules.
I always believed it is correct because the user expects that the accessing a dictionary instance via it's index should return something. The index does not exist, so it should throw an exception.
Any operation that is critical to working of an app should throw an exception. Return error messages is meant for optional operations which doest affect the final result.
This is my experience from .NET framework
ɐɥʇ ɐɥʞıl ǝʎıl ǝʞ ǝuɹɐɯ ıʞ ısıʞ ɐlɐʍ ǝʎ (: . But yes, even in communication, if error too is sent as a message it would create a confusion.
I think that the standard behavior is meaningful. After all, None is a value. What if your (key, value) pair is ("k", None)?
l = {}
l["k"] = None
print l["k"] # prints None
print l[42] # exception
Of course exception less one is a very bad design, given that it could lead to mis-information :)
Post a Comment
Subscribe to Post Comments [Atom]
<< Home