effectivepython
effectivepython copied to clipboard
Item #45: Incorrect condition handling
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
Indeed, I found this too!