missing? dictionary methods

Robert Kern rkern at ucsd.edu
Mon Mar 21 14:50:23 CET 2005


Antoon Pardon wrote:

> I would say the same reason that we have get. There is no
> reason to have a builtin get it is easily implemented
> like this:
> 
>   def get(dct, key, default):
> 
>     try:
>       return dct[key]
>     except KeyError:
>       return default
> 
> 
> I would go even so far that there is more reason to have a built-in
> safeset and make, than there is a reason to have a built-in get.
 >
> The reason is that a python implementation of safeset and make,
> will mean two accesses in the dictionary, once for the test and
> once for the assignment. This double access could be eliminated
> with a built-in. The get on the other hand does only one dictionary
> access, so having it implemeted in python is a lesser burden.

That's not true; they're on more or less the same level 
computation-wise. try:...except... doesn't relieve the burden; it's 
expensive.

For me, the issue boils down to how often such constructs are used. I 
don't think that I've ever run into use cases for safeset() and make(). 
dct.get(key, default) comes up *a lot*, and in places where speed can 
matter. Searching through the standard library can give you an idea how 
often.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter



More information about the Python-list mailing list