I\'m aware of raise ... from None
and have read How can I more easily suppress previous exceptions when I raise my own exception in response?.
However,
You have a few options here.
First, a cleaner version of what orlp suggested:
try:
value = cache_dict[key]
except KeyError:
try:
value = some_api.get_the_value(key)
except Exception as e:
raise e from None
cache_dict[key] = value
For the second option, I'm assuming there's a return value
hiding in there somewhere that you're not showing:
try:
return cache_dict[key]
except KeyError:
pass
value = cache_dict[key] = some_api.get_the_value(key)
return value
Third option, LBYL:
if key not in cache_dict:
cache_dict[key] = some_api.get_the_value(key)
return cache_dict[key]
For the bonus question, define your own dict subclass that defines __missing__
:
class MyCacheDict(dict):
def __missing__(self, key):
value = self[key] = some_api.get_the_value(key)
return value
Hope this helps!
You can try suppressing the context yourself:
try:
value = cache_dict[key]
except KeyError:
try:
value = some_api.get_the_value_via_web_service_call(key)
except Exception as e:
e.__context__ = None
raise
cache_dict[key] = value