bslatkin / effectivepython

Effective Python: Second Edition — Source Code and Errata for the Book
https://effectivepython.com
2.2k stars 710 forks source link

Item 45 Flawed code when delta is less than zero #100

Closed forrestgao closed 3 years ago

forrestgao commented 3 years ago
@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, but it's possible that self.quota_consumed is not 0, e.g.: 
        #bucket = NewBucket(6000) ➜ fill(bucket, 100) ➜ deduct(bucket, 10) ➜ fill(bucket, 50),  bucket.quota_consumed =10
        #AssertionError will be raised!
        #suggestion as follows:
        #assert self.quota_consumed == 0
        self.max_quota = amount + self.quota_consumed
    else:
        # Quota being consumed during the period
        assert self.max_quota >= delta
        self.quota_consumed = delta
bslatkin commented 3 years ago

Deduping with #94