3 ms·
Agree with that "try except" is better than "if else" for file handling ("with" is even better). I am not sure if "try except" is really faster than "if else"
by gbog 15y ago
Agree with that "try except" is better than "if else" for file handling ("with" is even better).
I am not sure if "try except" is really faster than "if else" in some edge cases in a memoization context, as you claim.
What I am sure is that in a didactic context, where you want people to understand code, something like:
if args not in stored_results:
stored_results[args] = fn(*args)
return stored_results[args]
is much better than that (from the OP):
try:
# try to get the cached result
return stored_results[args]
except KeyError:
# nothing was cached for those args. let's fix that.
result = stored_results[args] = fn(*args)
return result
- SpiderX 15y agoFor a memoize function, try/except is perfect. You gain a slight speed benefit from function calls that are memoized as compared to the "if x not in y", and since memoize is all about speeding up repetitive function calls, it's the most optimal choice. Using the "if x not in y" you are giving up speed of the "x is actually in the y" in exchange for a cheaper than "except", however if you are memoizing a function, chances are that the function is going to eat up processing power making your optimization of the "exceptional case" at the expense of the "normal case" not worth it. As far as people understanding code - this is a common pattern in python code, try / except should be easy for anyone to understand.