How to suppress displaying the parent exception (the cause) for subsequent exceptions

后端 未结 2 1570
遥遥无期
遥遥无期 2021-01-01 19:30

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,

相关标签:
2条回答
  • 2021-01-01 20:01

    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!

    0 讨论(0)
  • 2021-01-01 20:12

    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
    
    0 讨论(0)
提交回复
热议问题