添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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'

Is there a rationale behind removing a core function from a package in the middle of a major version? What happened to backward compatibility? What is the sense of suddenly saying this package should not nativley support this function? – raw-bin hood Nov 26, 2022 at 18:35

"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).

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.