Skip to content

Commit 37bf64c

Browse files
committed
Add xml.Node.__repr__()
The repr of an xml.Node only includes arguments where the value differs from the default. Do not print positional arg name in repr(xml.Node) "tag" is a non-optional positional argument, it makes for cleaner repr() output if we also omit the name.
1 parent c5cbe8c commit 37bf64c

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

base/src/xml.act

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,28 @@ n.text and c.tail for all children of n.
2323
def encode(self) -> str:
2424
NotImplemented
2525

26+
def __repr__(self):
27+
# Building the arguments to xml.Node() and skip arguments where the
28+
# current value equals the default. We do this with appending to a
29+
# string because that does not leak the *mut* effect, unlike appending
30+
# to a list.
31+
args = repr(self.tag)
32+
if len(self.nsdefs) != 0:
33+
args += f", nsdefs={repr(self.nsdefs)}"
34+
if self.prefix is not None:
35+
args += f", prefix={repr(self.prefix)}"
36+
if len(self.attributes) != 0:
37+
args += f", attributes={repr(self.attributes)}"
38+
if len(self.children) != 0:
39+
args += f", children={repr(self.children)}"
40+
if self.text is not None:
41+
args += f", text={repr(self.text)}"
42+
if self.tail is not None:
43+
args += f", tail={repr(self.tail)}"
44+
45+
return "xml.Node({args})"
46+
47+
2648
class XmlParseError(ValueError):
2749
"""Exception raised for XML parsing errors
2850

test/stdlib_tests/src/test_xml.act

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,8 @@ def _test_xml_namespace_attributes_undefined():
178178
testing.assertEqual(child_attr.1, 'child', "Undefined namespace: child attribute value not preserved")
179179
e = xml.encode(d)
180180
testing.assertEqual(e, test_xml, "Undefined namespace: roundtrip failed")
181+
182+
def _test_xml_repr():
183+
test_xml = """<data xmlns="http://default"><a xmlns:ns="http://foo" ns:operation="remove"><ns:b ns:type="element">text</ns:b></a></data>"""
184+
d = xml.decode(test_xml)
185+
testing.assertEqual(repr(d), "xml.Node('data', nsdefs=[(None, 'http://default')], children=[xml.Node('a', nsdefs=[('ns', 'http://foo')], attributes=[('ns:operation', 'remove')], children=[xml.Node('b', prefix='ns', attributes=[('ns:type', 'element')], text='text')])])")

0 commit comments

Comments
 (0)