utils.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """
  2. Utility functions
  3. """
  4. import uuid
  5. def chunks(it, n):
  6. """Split an iterator into chunks with ``n`` elements each.
  7. Examples
  8. # n == 2
  9. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2)
  10. >>> list(x)
  11. [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
  12. # n == 3
  13. >>> x = chunks(iter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 3)
  14. >>> list(x)
  15. [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
  16. """
  17. acc = []
  18. for i, item in enumerate(it):
  19. if i and not i % n:
  20. yield acc
  21. acc = []
  22. acc.append(item)
  23. yield acc
  24. def gen_unique_id():
  25. """Generate a unique id, having - hopefully - a very small chance of
  26. collission.
  27. For now this is provided by :func:`uuid.uuid4`.
  28. """
  29. return str(uuid.uuid4())
  30. def mitemgetter(*keys):
  31. """Like :func:`operator.itemgetter` but returns `None` on missing keys
  32. instead of raising :exc:`KeyError`."""
  33. return lambda dict_: map(dict_.get, keys)
  34. def get_full_cls_name(cls):
  35. return ".".join([cls.__module__,
  36. cls.__name__])