Opened 8 years ago

Closed 8 years ago

#35 closed defect (fixed)

Calls to ElementTree.Element.__nonzero__() raise FutureWarning

Reported by: flip Owned by: flip
Priority: minor Milestone:
Component: common Version:
Keywords: Cc:


Calls to ElementTree.Element.__nonzero__() raise FutureWarning

When Python code calls bool(an_object), Python calls the object's __nonzero__() method. ElementTree.Element.__nonzero__() returns True if the element has children, False otherwise. It also raises a FutureWarning stating that this behavior will change in the future. Since Python 2.7 is the last version of Python 2.x, I assume "in the future" means Python 3.x., although the warning & behavior is still unchanged as of Python 3.2.

Regardless of whether or not this ever changes, it has an immediate practical implication for Vespa. I filed this ticket to explain the problem and track the changes.

If a variable can hold an ElementTree.Element or None, we must explicitly test for None. In other words, this is bad:

if attributes:

This is correct:

if attributes is not None:

The former is bad because if attributes is a childless ElementTree.Element, it will evaluate to False and self.inflate(attributes) won't get called. In this context it's unlikely to matter because inflate() wouldn't need to do anything with a childless element, and passing a childless element would likely mean something is broken anyway. But we don't want to make such subtle assumptions.

Similarly, this is also to be avoided:

if source.find("some_tag_name"):

This is correct:

if source.find("some_tag_name") is not None:

Technical Note

A nasty complication is that the warning only appears when using the pure Python version of ElementTree. When using cElementTree (as our code always does), no warning appears.

For posterity's sake, here's the bash/sed command I used to change every import of cElementTree to ElementTree in my local source tree:

find . -name "*.py" -exec sed -i sed 's/import xml.etree.cElementTree as ElementTree/import xml.etree.ElementTree as ElementTree/g' '{}' \;

This relies on each import statement being formatted exactly the same way (whitespace and all) but we're pretty consistent so I think that's OK. Grepping for cElementTree found no hits after running the command above (except in sed backup files), so the command was a success.

Change History (1)

comment:1 Changed 8 years ago by flip

  • Resolution set to fixed
  • Status changed from new to closed

Fixed in r2924 and r2926

Note: See TracTickets for help on using tickets.