Source code for SDF.data_model.comment
from xml.etree.ElementTree import Element
from xml.sax.saxutils import escape, unescape
from SDF.data_model._helper_functions import unindent_xml_text, pop_element_text, element_is_empty
from SDF.data_model.abstract import XMLWritable
[docs]class Comment(XMLWritable):
"""Represents an SDF <comment> element"""
def __init__(self, comment: str):
self.comment = comment
@property
def comment(self):
return self.__comment
@comment.setter
def comment(self, _comment: str):
if not isinstance(_comment, str):
raise TypeError(f"Expected a string, got {type(_comment)}")
_comment = unindent_xml_text(_comment)
if not _comment or _comment.isspace():
raise ValueError("Comment cannot be empty")
self.__comment = _comment
[docs] def to_xml_element(self) -> Element:
element = Element("comment")
element.text = escape(self.comment)
return element
[docs] @classmethod
def from_xml_element(cls, element: Element) -> "Comment":
if element.tag != "comment":
raise ValueError(f"Expected a <comment> element, got {element.tag}")
text = pop_element_text(element)
if not element_is_empty(element):
raise ValueError("element is not empty")
return cls(unindent_xml_text(unescape(text)))
def __repr__(self):
return f"{self.__class__.__name__}({self.comment!r})"
def __eq__(self, other):
if isinstance(other, Comment):
return self.comment == other.comment
return False