]> granicus.if.org Git - python/commitdiff
http://bugs.python.org/issue8832
authorKristján Valur Jónsson <kristjan@ccpgames.com>
Wed, 9 Jun 2010 08:13:42 +0000 (08:13 +0000)
committerKristján Valur Jónsson <kristjan@ccpgames.com>
Wed, 9 Jun 2010 08:13:42 +0000 (08:13 +0000)
Issue minidom.unlink with a context manager

Doc/library/xml.dom.minidom.rst
Lib/test/test_minidom.py
Lib/xml/dom/minidom.py

index 5ece1ca13f8efa5a212205ddaea52e20a06e18db..792a8dcd59dff1655e04eb092c7762936203f0e3 100644 (file)
@@ -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="")
 
index 32863bf6aa082eeeb48f17ce89b834bc6be354a1..9a9acfbff3c4c990e4d23e2216ad19e22cf44c3b 100644 (file)
@@ -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()
index f4f4400d896bea113031638ce38e83adee77b194..7616b46fe0e98a1bf62884a0da459dd394011b24 100644 (file)
@@ -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.")