missing? dictionary methods

Antoon Pardon apardon at forel.vub.ac.be
Mon Mar 21 09:09:12 EST 2005


Op 2005-03-21, Robert Kern schreef <rkern at ucsd.edu>:
> 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.

I have always heard that try: ... except is relatively inexpensive
in python. Particularly if there is no exception raised.

> 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.

It is always hard to compare the popularity/usefullness of two things when
one is already implemented and the other is not. IME it is not that
uncommon to know in some part of the code that the keys you use should
already be in the dictionary or contrary that you know the key should
not already be in the dictionary.

-- 
Antoon Pardon



More information about the Python-list mailing list