spacepaste

  1.  
  2. from collections import deque, namedtuple
  3. HistoryItem = namedtuple("HistoryItem", ["timestamp", "data"])
  4. def process(data):
  5. pass
  6. class HistoryQueue:
  7. def __init__(self):
  8. self.hist = deque()
  9. def log_new(self, timestamp, data):
  10. item = HistoryItem(timestamp, data)
  11. self.hist.append(item)
  12. # Will IndexError out if self.hist gets empty, BAD
  13. def clear_old_1(self, now):
  14. while (now-self.hist[0].timestamp).total_seconds() >= 60:
  15. first_item = self.hist.popleft()
  16. process(first_item.data)
  17. # Will inadvertently catch possible IndexErrors in process(), making debugging painful, BAD
  18. def clear_old_2(self, now):
  19. try:
  20. while (now-self.hist[0].timestamp).total_seconds() >= 60:
  21. first_item = self.hist.popleft()
  22. process(first_item.data)
  23. except IndexError:
  24. pass
  25. # Will work as intended, uses try/except, and each individual portion of the code is readable and adheres to python best-practices, but together it looks like a giant mess with convoluted branching, hindering readability. Okay, but not great. Also, re-use name "first_item"
  26. def clear_old_3(self, now):
  27. while True:
  28. try:
  29. first_item = self.hist[0].timestamp
  30. except IndexError:
  31. break
  32. else:
  33. if (now - first_event.timestamp).total_seconds() < 60:
  34. break
  35. else:
  36. first_item = self.hist.popleft() # or just self.hist.popleft() and use first_item from before
  37. process(first_item.data)
  38. # A lot more readable, perhaps best, but is there a way to avoid LBYL? Also feels kind of hacky to put in that "len(self.hist) >= 1" in the start of the while expression to avoid IndexErrors in the second half, but perhaps this is indeed the best?
  39. def clear_old_4(self, now):
  40. while len(self.hist) >= 1 and (now - self.hist[0].timestamp) >= 60:
  41. first_item = sell.hist.popleft()
  42. process(first_item.data)
  43.