2 ms·
In Python e.g. instead of doing this: if key in some_dict: foo = some_dict[key] ... # A else: ... # B you would do this:
by carapace 5y ago
In Python e.g. instead of doing this:
if key in some_dict:
foo = some_dict[key]
... # A
else:
... # B
you would do this:
try:
foo = some_dict[key]
except KeyError:
... # B
else:
... # A
- albertzeyer 5y agoYou can do that, but: - Even in this example, I would assume that branch A is more often executed. So the zero cost optimization (which is about branch A) would improve this code performance. - I would argue, code which uses `some_dict.get(key, fallback)` or explicitly check `if key in some_dict: ...` is both more clean and more Pythonic. See also e.g.: https://mail.python.org/pipermail/python-dev/2014-March/133118.html https://mail.python.org/pipermail/python-dev/2014-March/1331...