utils.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. # -*- test-case-name: pytils.test.test_utils -*-
  3. """
  4. Misc utils for internal use
  5. """
  6. def check_length(value, length):
  7. """
  8. Checks length of value
  9. @param value: value to check
  10. @type value: C{str}
  11. @param length: length checking for
  12. @type length: C{int}
  13. @return: None when check successful
  14. @raise ValueError: check failed
  15. """
  16. _length = len(value)
  17. if _length != length:
  18. raise ValueError("length must be %d, not %d" % \
  19. (length, _length))
  20. def check_positive(value, strict=False):
  21. """
  22. Checks if variable is positive
  23. @param value: value to check
  24. @type value: C{integer types}, C{float} or C{Decimal}
  25. @return: None when check successful
  26. @raise ValueError: check failed
  27. """
  28. if not strict and value < 0:
  29. raise ValueError("Value must be positive or zero, not %s" % str(value))
  30. if strict and value <= 0:
  31. raise ValueError("Value must be positive, not %s" % str(value))
  32. def split_values(ustring, sep=','):
  33. """
  34. Splits unicode string with separator C{sep},
  35. but skips escaped separator.
  36. @param ustring: string to split
  37. @type ustring: C{str}
  38. @param sep: separator (default to ',')
  39. @type sep: C{str}
  40. @return: tuple of splitted elements
  41. """
  42. assert isinstance(ustring, str), "uvalue must be str, not %s" % type(ustring)
  43. # unicode have special mark symbol 0xffff which cannot be used in a regular text,
  44. # so we use it to mark a place where escaped column was
  45. ustring_marked = ustring.replace('\,', '\uffff')
  46. items = tuple([i.strip().replace('\uffff', ',') for i in ustring_marked.split(sep)])
  47. return items