2 ms·
It also depends on the language. For example, Python very much operates under the "ask for forgiveness, not permission" mantra, and I even see this used for dic
by tremon 4y ago
It also depends on the language. For example, Python very much operates under the "ask for forgiveness, not permission" mantra, and I even see this used for dict lookups. The number of times I encounter code like this:
try:
my_dict[key]
catch KeyException:
pass
rather than
if key in my_dict:
my_dict[key]
is astounding. I don't know what the performance difference is in Python though.
- 390iuwjhf 4y agoWhat about thing = my_dict.get(key) if thing is None: ...
- tremon 4y agoyes, my_dict.get() is my preferred solution too, if I can come up with a sensible default value or action. Otherwise, I do my_dict[key] without try/except. But I'm not sure if that's just a style preference or if there's a large performance difference in Python.
- rightbyte 4y agoThe later should require two lookups unless it is optimized away. Is there an easy way to get bytecode for Python snippets?