bpo-32424: Deprecate xml.etree.ElementTree.Element.copy() in favor of copy.copy(...
authorGordon P. Hemsley <me@gphemsley.org>
Tue, 10 Sep 2019 15:22:01 +0000 (11:22 -0400)
committerStefan Behnel <stefan_ml@behnel.de>
Tue, 10 Sep 2019 15:22:01 +0000 (16:22 +0100)
Lib/test/test_xml_etree.py
Lib/xml/etree/ElementTree.py
Misc/NEWS.d/next/Library/2019-04-28-10-34-19.bpo-32424.eqNPhM.rst [new file with mode: 0644]

index 87a6fa146462aa07a407492396987873a8bb0c8c..9fbb4ac1813acbf86d30fe600cdb70b96d6cbca7 100644 (file)
@@ -2211,6 +2211,35 @@ class BasicElementTest(ElementTestCase, unittest.TestCase):
         self.assertIsNot(element_foo.attrib, attrib)
         self.assertNotEqual(element_foo.attrib, attrib)
 
+    def test_copy(self):
+        # Only run this test if Element.copy() is defined.
+        if "copy" not in dir(ET.Element):
+            raise unittest.SkipTest("Element.copy() not present")
+
+        element_foo = ET.Element("foo", { "zix": "wyp" })
+        element_foo.append(ET.Element("bar", { "baz": "qix" }))
+
+        with self.assertWarns(DeprecationWarning):
+            element_foo2 = element_foo.copy()
+
+        # elements are not the same
+        self.assertIsNot(element_foo2, element_foo)
+
+        # string attributes are equal
+        self.assertEqual(element_foo2.tag, element_foo.tag)
+        self.assertEqual(element_foo2.text, element_foo.text)
+        self.assertEqual(element_foo2.tail, element_foo.tail)
+
+        # number of children is the same
+        self.assertEqual(len(element_foo2), len(element_foo))
+
+        # children are the same
+        for (child1, child2) in itertools.zip_longest(element_foo, element_foo2):
+            self.assertIs(child1, child2)
+
+        # attrib is a copy
+        self.assertEqual(element_foo2.attrib, element_foo.attrib)
+
     def test___copy__(self):
         element_foo = ET.Element("foo", { "zix": "wyp" })
         element_foo.append(ET.Element("bar", { "baz": "qix" }))
index e75200a1b8a306ece58744bf5b4f718d35f73edc..c8d898f32816dcae866aa3a077a17133ce21a765 100644 (file)
@@ -195,6 +195,13 @@ class Element:
         original tree.
 
         """
+        warnings.warn(
+            "elem.copy() is deprecated. Use copy.copy(elem) instead.",
+            DeprecationWarning
+            )
+        return self.__copy__()
+
+    def __copy__(self):
         elem = self.makeelement(self.tag, self.attrib)
         elem.text = self.text
         elem.tail = self.tail
diff --git a/Misc/NEWS.d/next/Library/2019-04-28-10-34-19.bpo-32424.eqNPhM.rst b/Misc/NEWS.d/next/Library/2019-04-28-10-34-19.bpo-32424.eqNPhM.rst
new file mode 100644 (file)
index 0000000..a60d68b
--- /dev/null
@@ -0,0 +1,3 @@
+Deprecate xml.etree.ElementTree.Element.copy() in favor of copy.copy().
+
+Patch by Gordon P. Hemsley