utils.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # This `uniq` implementation is taken from the Python `jsonschema` package.
  2. #
  3. # https://github.com/Julian/jsonschema
  4. #
  5. # Copyright (c) 2013 Julian Berman
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. import itertools
  25. def unbool(element, true=object(), false=object()):
  26. """
  27. A hack to make True and 1 and False and 0 unique for ``uniq``.
  28. """
  29. if element is True:
  30. return true
  31. elif element is False:
  32. return false
  33. return element
  34. def uniq(container):
  35. """
  36. Check if all of a container's elements are unique.
  37. Successively tries first to rely that the elements are hashable, then
  38. falls back on them being sortable, and finally falls back on brute
  39. force.
  40. """
  41. try:
  42. return len(set(unbool(i) for i in container)) == len(container)
  43. except TypeError:
  44. try:
  45. sort = sorted(unbool(i) for i in container)
  46. sliced = itertools.islice(sort, 1, None)
  47. for i, j in zip(sort, sliced):
  48. if i == j:
  49. return False
  50. except (NotImplementedError, TypeError):
  51. seen = []
  52. for e in container:
  53. e = unbool(e)
  54. if e in seen:
  55. return False
  56. seen.append(e)
  57. return True