pydanny/cached-property

threaded_cached_property can raise confusing exception

spyoungtech opened this issue · 0 comments

When the function decorated by threaded_cached_property raises an exception, rather than the exception from the user code being front-and-center, users are presented first with the cached property KeyError, only to see their real error further down the line.

Take for example the following code and resulting traceback.

class Monopoly(object):

    def __init__(self):
        self.boardwalk_price = 500

    @threaded_cached_property
    def boardwalk(self):
        self.boardwalk_price += 1/0
        return self.boardwalk_price

m = Monopoly()
m.boardwalk
Traceback (most recent call last):
  File "/Users/spencer.young/repos/cached-property/cached_property.py", line 70, in __get__
    return obj_dict[name]
KeyError: 'boardwalk'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "t.py", line 15, in <module>
    m.boardwalk
  File "/Users/spencer.young/repos/cached-property/cached_property.py", line 74, in __get__
    return obj_dict.setdefault(name, self.func(obj))
  File "t.py", line 11, in boardwalk
    self.boardwalk_price += 1/0
ZeroDivisionError: division by zero

The traceback presents first, a KeyError which could be confusing to the user. Instead, it would be nice if cached-property would avoid this in such a way that only the relevant ZeroDivisionError would surface.