Skip to content

Commit a95e60d

Browse files
pythongh-91447: Fix findtext to only give an empty string on None (pythonGH-91486)
The API documentation for [findtext](https://docs.python.org/3/library/xml.etree.elementtree.html#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 python#91447. Automerge-Triggered-By: GH:gvanrossum
1 parent 858c9a5 commit a95e60d

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

Lib/test/test_xml_etree.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2705,6 +2705,20 @@ def test_findtext_with_error(self):
27052705
except ZeroDivisionError:
27062706
pass
27072707

2708+
def test_findtext_with_falsey_text_attribute(self):
2709+
root_elem = ET.Element('foo')
2710+
sub_elem = ET.SubElement(root_elem, 'bar')
2711+
falsey = ["", 0, False, [], (), {}]
2712+
for val in falsey:
2713+
sub_elem.text = val
2714+
self.assertEqual(root_elem.findtext('./bar'), val)
2715+
2716+
def test_findtext_with_none_text_attribute(self):
2717+
root_elem = ET.Element('foo')
2718+
sub_elem = ET.SubElement(root_elem, 'bar')
2719+
sub_elem.text = None
2720+
self.assertEqual(root_elem.findtext('./bar'), '')
2721+
27082722
def test_findall_with_mutating(self):
27092723
e = ET.Element('foo')
27102724
e.extend([ET.Element('bar')])

Lib/xml/etree/ElementPath.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,8 @@ def findall(elem, path, namespaces=None):
416416
def findtext(elem, path, default=None, namespaces=None):
417417
try:
418418
elem = next(iterfind(elem, path, namespaces))
419-
return elem.text or ""
419+
if elem.text is None:
420+
return ""
421+
return elem.text
420422
except StopIteration:
421423
return default
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix findtext in the xml module to only give an empty string when the text
2+
attribute is set to None.

0 commit comments

Comments
 (0)