How to suppress display of parent exception (reason) for subsequent exceptions

I know raise ... from Noneand read. How can I more easily suppress previous exceptions when I raise my own exception in response? .

However, how can I achieve the same effect (suppressing the message "While processing the above exception, another exception") without control over the code that is executed from the except clause? I thought you could use this sys.exc_clear(), but this function does not exist in Python 3.

Why am I asking about this? I have a simple caching code that looks (simplified):

try:
    value = cache_dict[key]
except KeyError:
    value = some_api.get_the_value_via_web_service_call(key)
    cache_dict[key] = value

When an exception occurs in the API call, the output will be something like this:

Traceback (most recent call last):
  File ..., line ..., in ...
KeyError: '...'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ..., line ..., in ...
some_api.TheInterestingException: ...

, KeyError . , , , try/except (EAFP) (LBYL), Pythonic ( , -, , ).

, some_api raise X raise X from None ( ). , ?

(, : -, , cache_dict.setdefault(key, some_api.get_the_value_via_web_service_call(key)), setdefault , , . / ?)

+4
2

.

-, , orlp:

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

, return value -, :

try:
    return cache_dict[key]
except KeyError:
    pass
value = cache_dict[key] = some_api.get_the_value(key)
return value

, LBYL:

if key not in cache_dict:
    cache_dict[key] = some_api.get_the_value(key)
return cache_dict[key]

dict, __missing__:

class MyCacheDict(dict):

    def __missing__(self, key):
        value = self[key] = some_api.get_the_value(key)
        return value

, !

+3

:

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
0

All Articles