Friday, September 2, 2005

getdefault method for python dictionary

In this blog:

http://blogs.nuxeo.com/sections/blogs/ruslan_spivak/2005_09_01_btrees-setdefault

Blogger says that Python's dictionary method, 'setdefault' without explicit default
is confusing and useless. Now I think there should be a 'getdefault' method
which also requires two explicit arguments, it will return explicit default
if no key exists.

Here is an example:

>>> d = {1: None}
>>> print d.getdefault(1, 'Hi')
None
>>> print d.getdefault(2, 'Hi')
'Hi'

Hmm.. there is already a 'get' method. If we have 'getdefault'
then 'get' can be deprecated, Here is the reason:

>>> d = {1: None}
>>> print d.get(1)
None
>>> print d.get(2)
None

See, here I didn't thought about any use cases.