Skip to content

Commit 6bd058e

Browse files
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 40db798) Co-authored-by: scoder <stefan_ml@behnel.de>
1 parent 09a7b3b commit 6bd058e

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

Doc/library/xml.etree.elementtree.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,12 +249,18 @@ We can remove elements using :meth:`Element.remove`. Let's say we want to
249249
remove all countries with a rank higher than 50::
250250

251251
>>> for country in root.findall('country'):
252+
... # using root.findall() to avoid removal during traversal
252253
... rank = int(country.find('rank').text)
253254
... if rank > 50:
254255
... root.remove(country)
255256
...
256257
>>> tree.write('output.xml')
257258

259+
Note that concurrent modification while iterating can lead to problems,
260+
just like when iterating and modifying Python lists or dicts.
261+
Therefore, the example first collects all matching elements with
262+
``root.findall()``, and only then iterates over the list of matches.
263+
258264
Our XML now looks like this:
259265

260266
.. code-block:: xml

0 commit comments

Comments
 (0)