Index: Doc/library/xml.dom.minidom.rst =================================================================== --- Doc/library/xml.dom.minidom.rst (revision 81561) +++ Doc/library/xml.dom.minidom.rst (working copy) @@ -114,7 +114,14 @@ 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="") Write XML to the writer object. The writer should have a :meth:`write` method Index: Lib/test/test_minidom.py =================================================================== --- Lib/test/test_minidom.py (revision 81561) +++ Lib/test/test_minidom.py (working copy) @@ -230,6 +230,10 @@ dom = parse(tstfile) dom.unlink() + def testContext(self): + with parse(tstfile) as dom: + self.confirm(dom) + def testElement(self): dom = Document() dom.appendChild(dom.createElement("abc")) Index: Lib/xml/dom/minidom.py =================================================================== --- Lib/xml/dom/minidom.py (revision 81561) +++ Lib/xml/dom/minidom.py (working copy) @@ -268,6 +268,14 @@ 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.")