datastructures.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """
  2. Custom Datastructures
  3. """
  4. from UserList import UserList
  5. import traceback
  6. class PositionQueue(UserList):
  7. """A positional queue of a specific length, with slots that are either
  8. filled or unfilled. When all of the positions are filled, the queue
  9. is considered :meth:`full`.
  10. :param length: see :attr:`length`.
  11. .. attribute:: length
  12. The number of items required for the queue to be considered full.
  13. """
  14. class UnfilledPosition(object):
  15. """Describes an unfilled slot."""
  16. def __init__(self, position):
  17. self.position = position
  18. def __init__(self, length):
  19. self.length = length
  20. self.data = map(self.UnfilledPosition, xrange(length))
  21. def full(self):
  22. """Returns ``True`` if all of the slots has been filled."""
  23. return len(self) >= self.length
  24. def __len__(self):
  25. """``len(self)`` -> number of slots filled with real values."""
  26. return len(self.filled)
  27. @property
  28. def filled(self):
  29. """Returns the filled slots as a list."""
  30. return filter(lambda v: not isinstance(v, self.UnfilledPosition),
  31. self.data)
  32. class ExceptionInfo(object):
  33. """Exception wrapping an exception and its traceback.
  34. :param exc_info: The exception tuple info as returned by
  35. :func:`traceback.format_exception`.
  36. .. attribute:: exception
  37. The original exception.
  38. .. attribute:: traceback
  39. A traceback from the point when :attr:`exception` was raised.
  40. """
  41. def __init__(self, exc_info):
  42. type_, exception, tb = exc_info
  43. self.exception = exception
  44. self.traceback = '\n'.join(traceback.format_exception(*exc_info))
  45. def __str__(self):
  46. return str(self.exception)