thoughts, ideas, code and other things...

Saturday, August 07, 2010

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):
return self.get(key)
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

Labels: , ,


At August 8, 2010 at 6:22 PM , Blogger Manish said...

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

At August 8, 2010 at 6:28 PM , Blogger Abhishek Mishra said...

ɐɥʇ ɐɥʞıl ǝʎıl ǝʞ ǝuɹɐɯ ıʞ ısıʞ ɐlɐʍ ǝʎ (: . But yes, even in communication, if error too is sent as a message it would create a confusion.

At September 1, 2010 at 9:14 PM , Anonymous Dheeraj said...

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

At September 1, 2010 at 9:23 PM , Blogger Abhishek Mishra said...

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