]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-91447: Fix findtext to only give an empty string on None (GH-91486)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 1 Aug 2022 21:22:33 +0000 (14:22 -0700)
committerGitHub <noreply@github.com>
Mon, 1 Aug 2022 21:22:33 +0000 (14:22 -0700)
The API documentation for [findtext](https://docs.python.org/3/library/xml.etree.elementtree.htmlGH-xml.etree.ElementTree.Element.findtext) states that this function gives back an empty string on "no text content." With the previous implementation, this would give back a empty string even on text content values such as 0 or False. This patch attempts to resolve that by only giving back an empty string if the text attribute is set to `None`. Resolves GH-91447.

Automerge-Triggered-By: GH:gvanrossum
(cherry picked from commit a95e60db748ec6f2c19b5710c11f62e1e4d669f4)

Co-authored-by: Eugene Triguba <eugenetriguba@gmail.com>
Lib/test/test_xml_etree.py
Lib/xml/etree/ElementPath.py
Misc/NEWS.d/next/Library/2022-04-12-18-05-40.gh-issue-91447.N_Fs4H.rst [new file with mode: 0644]

index afa4641e6906b70d04bb8dc1414fdb70a0e081cd..63b6725af89704f66c6c0300e100cfdacb525597 100644 (file)
@@ -2734,6 +2734,20 @@ class BadElementPathTest(ElementTestCase, unittest.TestCase):
         except ZeroDivisionError:
             pass
 
+    def test_findtext_with_falsey_text_attribute(self):
+        root_elem = ET.Element('foo')
+        sub_elem = ET.SubElement(root_elem, 'bar')
+        falsey = ["", 0, False, [], (), {}]
+        for val in falsey:
+            sub_elem.text = val
+            self.assertEqual(root_elem.findtext('./bar'), val)
+
+    def test_findtext_with_none_text_attribute(self):
+        root_elem = ET.Element('foo')
+        sub_elem = ET.SubElement(root_elem, 'bar')
+        sub_elem.text = None
+        self.assertEqual(root_elem.findtext('./bar'), '')
+
     def test_findall_with_mutating(self):
         e = ET.Element('foo')
         e.extend([ET.Element('bar')])
index cd3c354d0813ee4b55000431306736c653331d51..dc6bd28c03137de1968b41d2b857dc57f6549f08 100644 (file)
@@ -416,6 +416,8 @@ def findall(elem, path, namespaces=None):
 def findtext(elem, path, default=None, namespaces=None):
     try:
         elem = next(iterfind(elem, path, namespaces))
-        return elem.text or ""
+        if elem.text is None:
+            return ""
+        return elem.text
     except StopIteration:
         return default
diff --git a/Misc/NEWS.d/next/Library/2022-04-12-18-05-40.gh-issue-91447.N_Fs4H.rst b/Misc/NEWS.d/next/Library/2022-04-12-18-05-40.gh-issue-91447.N_Fs4H.rst
new file mode 100644 (file)
index 0000000..6f9be2d
--- /dev/null
@@ -0,0 +1,2 @@
+Fix findtext in the xml module to only give an empty string when the text
+attribute is set to None.