From 17173cfe7b5f880c02a8f9468f17607ec84e5b39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kristj=C3=A1n=20Valur=20J=C3=B3nsson?= Date: Wed, 9 Jun 2010 08:13:42 +0000 Subject: http://bugs.python.org/issue8832 Issue minidom.unlink with a context manager --- Doc/library/xml.dom.minidom.rst | 7 +++++++ Lib/test/test_minidom.py | 7 +++++++ Lib/xml/dom/minidom.py | 8 ++++++++ 3 files changed, 22 insertions(+) diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst index 5ece1ca..792a8dc 100644 --- a/Doc/library/xml.dom.minidom.rst +++ b/Doc/library/xml.dom.minidom.rst @@ -114,6 +114,13 @@ module documentation. This section lists the differences between the API and to be called on the :class:`Document` object, but may be called on child nodes to discard children of that node. + You can avoid calling this method explicitly by using the :keyword:`with` + statement. The following code will automatically unlink *dom* when the + :keyword:`with` block is exited:: + + with xml.dom.minidom.parse(datasource) as dom: + ... # Work with dom. + .. method:: Node.writexml(writer, indent="", addindent="", newl="", encoding="") diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py index 32863bf..9a9acfb 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -228,7 +228,14 @@ class MinidomTest(unittest.TestCase): def testUnlink(self): dom = parse(tstfile) + self.assertTrue(dom.childNodes) dom.unlink() + self.assertFalse(dom.childNodes) + + def testContext(self): + with parse(tstfile) as dom: + self.assertTrue(dom.childNodes) + self.assertFalse(dom.childNodes) def testElement(self): dom = Document() diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py index f4f4400..7616b46 100644 --- a/Lib/xml/dom/minidom.py +++ b/Lib/xml/dom/minidom.py @@ -268,6 +268,14 @@ class Node(xml.dom.Node): self.previousSibling = None self.nextSibling = None + # A Node is its own context manager, to ensure that an unlink() call occurs. + # This is similar to how a file object works. + def __enter__(self): + return self + + def __exit__(self, et, ev, tb): + self.unlink() + defproperty(Node, "firstChild", doc="First child node, or None.") defproperty(Node, "lastChild", doc="Last child node, or None.") defproperty(Node, "localName", doc="Namespace-local name of this node.") -- cgit v0.12