From: Miss Skeleton (bot) <31488909+miss-islington@users.noreply.github.com> Date: Sun, 4 Oct 2020 23:56:56 +0000 (-0700) Subject: bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifyin... X-Git-Tag: v3.9.1rc1~200 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=d5719247ba32b3ac700454bad9a9e2cc7edeac6a;p=thirdparty%2FPython%2Fcpython.git bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifying an XML tree while iterating over it. (GH-22464) (GH-22554) (cherry picked from commit 40db798692ca783fc2163656f196ac77e8b9e792) Co-authored-by: scoder Co-authored-by: scoder --- diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst index 7725e4d158d4..f4bccf660981 100644 --- a/Doc/library/xml.etree.elementtree.rst +++ b/Doc/library/xml.etree.elementtree.rst @@ -251,12 +251,18 @@ We can remove elements using :meth:`Element.remove`. Let's say we want to remove all countries with a rank higher than 50:: >>> for country in root.findall('country'): + ... # using root.findall() to avoid removal during traversal ... rank = int(country.find('rank').text) ... if rank > 50: ... root.remove(country) ... >>> tree.write('output.xml') +Note that concurrent modification while iterating can lead to problems, +just like when iterating and modifying Python lists or dicts. +Therefore, the example first collects all matching elements with +``root.findall()``, and only then iterates over the list of matches. + Our XML now looks like this: .. code-block:: xml