Skip to content

Commit 40db798

Browse files
authored
bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifying an XML tree while iterating over it. (pythonGH-22464)
1 parent 9ece9cd commit 40db798

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

Doc/library/xml.etree.elementtree.rst

+6
Original file line numberDiff line numberDiff line change
@@ -251,12 +251,18 @@ We can remove elements using :meth:`Element.remove`. Let's say we want to
251251
remove all countries with a rank higher than 50::
252252

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

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

262268
.. code-block:: xml

0 commit comments

Comments
 (0)