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.

alphabeticalattributes.py 919B

1234567891011121314151617181920212223242526272829
  1. from __future__ import absolute_import, division, unicode_literals
  2. from . import base
  3. from collections import OrderedDict
  4. def _attr_key(attr):
  5. """Return an appropriate key for an attribute for sorting
  6. Attributes have a namespace that can be either ``None`` or a string. We
  7. can't compare the two because they're different types, so we convert
  8. ``None`` to an empty string first.
  9. """
  10. return (attr[0][0] or ''), attr[0][1]
  11. class Filter(base.Filter):
  12. """Alphabetizes attributes for elements"""
  13. def __iter__(self):
  14. for token in base.Filter.__iter__(self):
  15. if token["type"] in ("StartTag", "EmptyTag"):
  16. attrs = OrderedDict()
  17. for name, value in sorted(token["data"].items(),
  18. key=_attr_key):
  19. attrs[name] = value
  20. token["data"] = attrs
  21. yield token