counter.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- Mode: Python -*-
  2. # It is tempting to add an __int__ method to this class, but it's not
  3. # a good idea. This class tries to gracefully handle integer
  4. # overflow, and to hide this detail from both the programmer and the
  5. # user. Note that the __str__ method can be relied on for printing out
  6. # the value of a counter:
  7. #
  8. # >>> print 'Total Client: %s' % self.total_clients
  9. #
  10. # If you need to do arithmetic with the value, then use the 'as_long'
  11. # method, the use of long arithmetic is a reminder that the counter
  12. # will overflow.
  13. from supervisor.compat import long
  14. class counter:
  15. """general-purpose counter"""
  16. def __init__ (self, initial_value=0):
  17. self.value = initial_value
  18. def increment (self, delta=1):
  19. result = self.value
  20. try:
  21. self.value = self.value + delta
  22. except OverflowError:
  23. self.value = long(self.value) + delta
  24. return result
  25. def decrement (self, delta=1):
  26. result = self.value
  27. try:
  28. self.value = self.value - delta
  29. except OverflowError:
  30. self.value = long(self.value) - delta
  31. return result
  32. def as_long (self):
  33. return long(self.value)
  34. def __nonzero__ (self):
  35. return self.value != 0
  36. __bool__ = __nonzero__
  37. def __repr__ (self):
  38. return '<counter value=%s at %x>' % (self.value, id(self))
  39. def __str__ (self):
  40. s = str(long(self.value))
  41. if s[-1:] == 'L':
  42. s = s[:-1]
  43. return s