1

I am using xml.etree in Python to parse a SOAP response (don't ask...). The response contains a <Success /> element.

I go and search it, find it and get an xml.etree.ElementTree.Element instance, let's call it my_element.

Yet said instance evaluates to False

  • bool(my_element) is False
  • my_element.__nonzero__() is False (using Python 2.7, otherwise I'd check __bool__() of course).

I assume that is because my_element.text is empty, as <Success /> is an empty xml element.

I also assume this is a pythonic thing to do, as empty lists and dicts behave similarly - even though I think the meaning of an empty but existing XML element is different: What is the most pythonic way to check whether it is there?

Is it really the following?

from xml.etree.ElementTree import Element
...
if isinstance(my_element, Element):
  • 1
    You didn't list the method you're using to find it. But it probably returns None if it doesn't find one. So... if my_element is not None – clockwatcher Aug 02 '16 at 16:23
  • Perhaps `succeeded = myTree.find('Success') is not None`. Ideally, the response should have been designed to have the Success element to always be present and set to True or False. – Steven Rumbalski Aug 02 '16 at 16:26
  • 1
    Does this answer your question? [Why does bool(xml.etree.ElementTree.Element) evaluate to False?](https://stackoverflow.com/questions/20129996/why-does-boolxml-etree-elementtree-element-evaluate-to-false) – Joe May 21 '21 at 12:02

1 Answers1

1

No, isinstance is not the recommend way to check for non-existence of an Element.

From the docs:

Caution: Elements with no subelements will test as False. This behavior will change in future versions. Use specific len(elem) or elem is None test instead.

From the source:

   warnings.warn(
        "The behavior of this method will change in future versions.  "
        "Use specific 'len(elem)' or 'elem is not None' test instead.",
        FutureWarning, stacklevel=2
        )

To test for the non-existence of an element, do something like this:

my_element = tree.find('.//Success')
if my_element is not None:
    do_something(my_element)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 1
    didn't see the warning. Why would an element return false if it has no children? Can't understand that decision. – Johnny May 17 '17 at 09:39
  • 1
    This defies all logical standards. Its testing for the existence of children attached to the element instead of the element it just returned. It should have implemented a test for children separately as that is a different context to the currently found element. Not a fan. – Peter Moore Jul 25 '23 at 15:13
  • 1
    Yes, it is illogical. And that, I presume is why "this behavior will change in future versions." – Robᵩ Jul 26 '23 at 20:00