Hacker News new | past | comments | ask | show | jobs | submit login

The try/except is the preferred python way of doing things. In Python, try/except is cheap, and in the case where the try actually succeeds, you can gain a slight performance benefit. In this case, since performance is the goal, it is perfect for memoize.



I think subtle optimization should be left aside in a tutorial. Try except is a good way to handle many cases that are not exceptions, like when reaching the end of an iteration, but I never heard that it was "the preferred way" for checking the presence of a key in a dict. I believe the "if in" construct is cleaner, clearer and "pythoniker", if you don't mind the Housism.


"if in" is not the preferred way to check for the presence of a key in a dict. You should use setdefault. The thing is, you aren't searching for a key in a dict only. You're memoizing. And try/except is the most efficient way to do that. This article isn't teaching you how to program, it's teaching decorators.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: