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.

44 lines
1.1 KiB

4 years ago
  1. from collections import OrderedDict
  2. import six
  3. def _attr_key(attr):
  4. """Returns appropriate key for sorting attribute names
  5. Attribute names are a tuple of ``(namespace, name)`` where namespace can be
  6. ``None`` or a string. These can't be compared in Python 3, so we conver the
  7. ``None`` to an empty string.
  8. """
  9. key = (attr[0][0] or ''), attr[0][1]
  10. return key
  11. def alphabetize_attributes(attrs):
  12. """Takes a dict of attributes (or None) and returns them alphabetized"""
  13. if not attrs:
  14. return attrs
  15. return OrderedDict(
  16. [(k, v) for k, v in sorted(attrs.items(), key=_attr_key)]
  17. )
  18. def force_unicode(text):
  19. """Takes a text (Python 2: str/unicode; Python 3: unicode) and converts to unicode
  20. :arg str/unicode text: the text in question
  21. :returns: text as unicode
  22. :raises UnicodeDecodeError: if the text was a Python 2 str and isn't in
  23. utf-8
  24. """
  25. # If it's already unicode, then return it
  26. if isinstance(text, six.text_type):
  27. return text
  28. # If not, convert it
  29. return six.text_type(text, 'utf-8', 'strict')