effectivepython icon indicating copy to clipboard operation
effectivepython copied to clipboard

Item #45: Incorrect condition handling

Open chenlu11 opened this issue 5 years ago • 1 comments

In the book tip 30 and example_code/item_45.py

# Quota being consumed during the period
assert self.max_quota >= self.quota_consumed
self.quota_consumed += delta

should be corrected to

class NewBucket:
    def __init__(self, period):
        self.period_delta = timedelta(seconds=period)
        self.reset_time = datetime.now()
        self.max_quota = 0
        self.quota_consumed = 0
    def __repr__(self):
        return (f'NewBucket(max_quota={self.max_quota}, '
                f'quota_consumed={self.quota_consumed})')
    @property
    def quota(self):
        return self.max_quota - self.quota_consumed
    @quota.setter
    def quota(self, amount):
        delta = self.max_quota - amount
        if amount == 0:
            # Quota being reset for a new period
            self.quota_consumed = 0
            self.max_quota = 0
        elif delta < 0:
            # Quota being filled for the new period
            assert self.quota_consumed == 0
            self.max_quota = amount
        else:
            # Quota being consumed during the period
            assert self.max_quota >= delta
            self.quota_consumed = delta

chenlu11 avatar Jan 17 '21 22:01 chenlu11

Indeed, I found this too!

forrestgao avatar Apr 13 '21 01:04 forrestgao