container.py 889 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright (c) 2010-2024 openpyxl
  2. """
  3. Utility list for top level containers that contain one type of element
  4. Provides the necessary API to read and write XML
  5. """
  6. from openpyxl.xml.functions import Element
  7. class ElementList(list):
  8. @property
  9. def tagname(self):
  10. raise NotImplementedError
  11. @property
  12. def expected_type(self):
  13. raise NotImplementedError
  14. @classmethod
  15. def from_tree(cls, tree):
  16. l = [cls.expected_type.from_tree(el) for el in tree]
  17. return cls(l)
  18. def to_tree(self):
  19. container = Element(self.tagname)
  20. for el in self:
  21. container.append(el.to_tree())
  22. return container
  23. def append(self, value):
  24. if not isinstance(value, self.expected_type):
  25. raise TypeError(f"Value must of type {self.expected_type} {type(value)} provided")
  26. super().append(value)