Wrote a memoize function: I do not mind feedback

Mark Lawrence breamoreboy at yahoo.co.uk
Wed Apr 29 10:58:44 CEST 2015


On 29/04/2015 09:04, Cecil Westerhof wrote:
> Op Wednesday 29 Apr 2015 09:02 CEST schreef Ian Kelly:
>
>> On Wed, Apr 29, 2015 at 12:06 AM, Cecil Westerhof <Cecil at decebal.nl> wrote:
>>> Op Monday 27 Apr 2015 22:35 CEST schreef Albert-Jan Roskam:
>>>> def some_func(arg, _memoize={}):
>>>> try:
>>>> return _memoize[arg]
>>>> except KeyError:
>>>> result = some_expensive_operation(arg)
>>>> _memoize[arg] = result
>>>> return result
>>>
>>> That is in a way the same as what I do, except I do not use an
>>> exception. Iunderstand it is not as expensive as it was anymore,
>>> but I do not like to use an exception (when not necessary).
>>
>> It's useful to keep in mind which case it is that you're trying to
>> optimize. The expensive case for exceptions is when one actually
>> gets raised. A try that doesn't raise an exception is pretty cheap,
>> probably cheaper than looking up the key in the dict twice as the
>> code you linked does. Compare:
>
> It is not only performance wise, I find the code without the try also
> better looking. But that is very personally I suppose.
>

You might find this interesting 
http://www.jeffknupp.com/blog/2013/02/06/write-cleaner-python-use-exceptions/

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list