Using exceptions for flow control has always been a bad idea, despite what they might have said. Perhaps they are generating that message lazily though?
On the other hand it's not like Python really cares about performance....
On the other hand it's not like Python really cares about performance....
[heavy green check mark]
try:
data = collection['key']
except KeyError:
data = ..try something else..
[red x] if 'key' in collection:
data = collection['key']
else:
data = ..try something else..
The latter form also has the genuine disadvantage that nothing ensures the two keys are the same. I've seen typos there somewhat often in code reviews.https://realpython.com/python-lbyl-vs-eafp/#errors-and-excep...
data = collection.get("key")
if data is not None:
...
else:
.... data = collection.get("key")
if data:
...
else:
... missing = object()
data = collection.get("key", missing)
if data is missing:
...
else:
.... for key in possible_keys:
if key in collection:
...
is fine and isn’t subject to your disadvantage.