Feature suggestion -- return if true
Aahz
aahz at pythoncraft.com
Mon Apr 18 12:11:08 EDT 2011
In article <mailman.461.1303043638.9059.python-list at python.org>,
D'Arcy J.M. Cain <darcy at druid.net> wrote:
>On Sun, 17 Apr 2011 16:21:53 +1200
>Gregory Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> My idiom for fetching from a cache looks like this:
>>
>> def get_from_cache(x):
>> y = cache.get(x)
>> if not y:
>> y = compute_from(x)
>> cache[x] = y
>> return y
>
>I prefer not to create and destroy objects needlessly.
>
> def get_from_cache(x):
> if not x in cache:
> cache[x] = compute_from(x)
> return cache[x]
Aside from Steven's entirely appropriate pointed question, I find this
more readable:
if x not in cache:
Without testing, I'm not sure, but I believe it's more efficient, too
(creates fewer bytecodes).
--
Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/
"At Resolver we've found it useful to short-circuit any doubt and just
refer to comments in code as 'lies'. :-)"
--Michael Foord paraphrases Christian Muirhead on python-dev, 2009-03-22
More information about the Python-list
mailing list