You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.7 KiB

4 years ago
  1. import six
  2. def str_to_unicode(text, encoding=None, errors='strict'):
  3. if encoding is None:
  4. encoding = 'utf-8'
  5. if isinstance(text, bytes):
  6. return text.decode(encoding, errors)
  7. return text
  8. def unicode_to_str(text, encoding=None, errors='strict'):
  9. if encoding is None:
  10. encoding = 'utf-8'
  11. if isinstance(text, six.text_type):
  12. return text.encode(encoding, errors)
  13. return text
  14. def to_unicode(text, encoding=None, errors='strict'):
  15. """Return the unicode representation of a bytes object `text`. If `text`
  16. is already an unicode object, return it as-is."""
  17. if isinstance(text, six.text_type):
  18. return text
  19. if not isinstance(text, (bytes, six.text_type)):
  20. raise TypeError('to_unicode must receive a bytes, str or unicode '
  21. 'object, got %s' % type(text).__name__)
  22. if encoding is None:
  23. encoding = 'utf-8'
  24. return text.decode(encoding, errors)
  25. def to_bytes(text, encoding=None, errors='strict'):
  26. """Return the binary representation of `text`. If `text`
  27. is already a bytes object, return it as-is."""
  28. if isinstance(text, bytes):
  29. return text
  30. if not isinstance(text, six.string_types):
  31. raise TypeError('to_bytes must receive a unicode, str or bytes '
  32. 'object, got %s' % type(text).__name__)
  33. if encoding is None:
  34. encoding = 'utf-8'
  35. return text.encode(encoding, errors)
  36. def to_native_str(text, encoding=None, errors='strict'):
  37. """ Return str representation of `text`
  38. (bytes in Python 2.x and unicode in Python 3.x). """
  39. if six.PY2:
  40. return to_bytes(text, encoding, errors)
  41. else:
  42. return to_unicode(text, encoding, errors)