util.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Functions that are nice to have but really should be in the python std lib"""
  2. def flatten(xs):
  3. """Recursively flattens a list of lists of lists (arbitrarily, non-uniformly
  4. deep) into a single big list."""
  5. res = []
  6. def loop(ys):
  7. for i in ys:
  8. if isinstance(i, list): loop(i)
  9. elif i is None: pass
  10. else: res.append(i)
  11. loop(xs)
  12. return res
  13. def singleton(cls):
  14. """Decorates a class to turn it into a singleton."""
  15. obj = cls()
  16. obj.__name__ = cls.__name__
  17. return obj
  18. def merge_dicts(my_dicts):
  19. """Combines a bunch of dictionaries together, later dictionaries taking
  20. precedence if there is a key conflict"""
  21. return dict((k,v) for d in my_dicts for (k,v) in d.items())
  22. class Lazy:
  23. def __init__(self, thunk):
  24. self.thunk = thunk
  25. self.val = None
  26. def __call__(self):
  27. if self.val is None:
  28. self.val = [self.thunk()]
  29. return self.val[0]
  30. def distinct(l):
  31. """Builds a new list with all duplicates removed"""
  32. s = []
  33. for i in l:
  34. if i not in s:
  35. s.append(i)
  36. return s
  37. def register(array):
  38. """A decorator to add things to lists without stomping over its value"""
  39. def x(val):
  40. array.append(val)
  41. return val
  42. return x