Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getchildren removed for python 3.9

I read the following: "Deprecated since version 3.2, will be removed in version 3.9: Use list(elem) or iteration." (https://docs.python.org/3.8/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren)

My code works for python 3.8 and below :

tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.getchildren()[0].attrib['ID'])

However, when I try to update it for python 3.9, I am unable to

tree = ET.parse("....xml")
root = tree.getroot()
getID= (root.list(elem)[0].attrib['ID'])

I get the following errors AttributeError: 'xml.etree.ElementTree.Element' object has no attribute 'list'

like image 761
QueenBee Avatar asked Jan 24 '23 10:01

QueenBee


2 Answers

"Use list(elem) or iteration" means literally list(root), not root.list(). The following will work:

getID = list(root)[0].attrib['ID']

You can wrap any iterable in a list, and the deprecation note specifically tells you root is iterable. Since it's rather inefficient to allocate a list for just one element, you can get the iterator and pull the first element from that:

getID = next(iter(root)).attrib['ID']

This is a more compact notation for

for child in root:
    getID = child.attrib['ID']
    break

The major difference is where the error will get raised when there is no child (directly by next vs when you try to access the non-existent getID variable).

like image 64
Mad Physicist Avatar answered Jan 27 '23 00:01

Mad Physicist


the error is indicating you should write this:

getID = list(root)[0].attrib['ID']

invoking list iterates over the root element giving its children and at the same time converting it to a list which can be indexed

like image 30
Anthony Sottile Avatar answered Jan 27 '23 00:01

Anthony Sottile