/django/utils/itercompat.py

https://github.com/Tippr/django · Python · 50 lines · 33 code · 6 blank · 11 comment · 12 complexity · 166a3137ffcac6120ac6f922e1109400 MD5 · raw file

  1. """
  2. Providing iterator functions that are not in all version of Python we support.
  3. Where possible, we try to use the system-native version and only fall back to
  4. these implementations if necessary.
  5. """
  6. import itertools
  7. import warnings
  8. # Fallback for Python 2.5
  9. def product(*args, **kwds):
  10. """
  11. Taken from http://docs.python.org/library/itertools.html#itertools.product
  12. """
  13. # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
  14. # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
  15. pools = map(tuple, args) * kwds.get('repeat', 1)
  16. result = [[]]
  17. for pool in pools:
  18. result = [x+[y] for x in result for y in pool]
  19. for prod in result:
  20. yield tuple(prod)
  21. if hasattr(itertools, 'product'):
  22. product = itertools.product
  23. def is_iterable(x):
  24. "A implementation independent way of checking for iterables"
  25. try:
  26. iter(x)
  27. except TypeError:
  28. return False
  29. else:
  30. return True
  31. def all(iterable):
  32. warnings.warn("django.utils.itercompat.all is deprecated; use the native version instead",
  33. PendingDeprecationWarning)
  34. for item in iterable:
  35. if not item:
  36. return False
  37. return True
  38. def any(iterable):
  39. warnings.warn("django.utils.itercompat.any is deprecated; use the native version instead",
  40. PendingDeprecationWarning)
  41. for item in iterable:
  42. if item:
  43. return True
  44. return False