summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorMiss Skeleton (bot) <31488909+miss-islington@users.noreply.github.com>2020-10-04 23:23:43 (GMT)
committerGitHub <noreply@github.com>2020-10-04 23:23:43 (GMT)
commit6bd058e0ff5d4a63fb35f6d45161cdf51cb68c58 (patch)
tree3264817dd5b8962aaf50973b5e5b4d3efd10b3fd /Doc
parent09a7b3b618cd02694a0bc8abfa24c75f0e659407 (diff)
downloadcpython-6bd058e0ff5d4a63fb35f6d45161cdf51cb68c58.zip
cpython-6bd058e0ff5d4a63fb35f6d45161cdf51cb68c58.tar.gz
cpython-6bd058e0ff5d4a63fb35f6d45161cdf51cb68c58.tar.bz2
bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifying an XML tree while iterating over it. (GH-22464)
(cherry picked from commit 40db798692ca783fc2163656f196ac77e8b9e792) Co-authored-by: scoder <stefan_ml@behnel.de>
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/xml.etree.elementtree.rst6
1 files changed, 6 insertions, 0 deletions
diff --git a/Doc/library/xml.etree.elementtree.rst b/Doc/library/xml.etree.elementtree.rst
index 44ac52a..e4aedd1 100644
--- a/Doc/library/xml.etree.elementtree.rst
+++ b/Doc/library/xml.etree.elementtree.rst
@@ -249,12 +249,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