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 40db798692)

Co-authored-by: scoder <stefan_ml@behnel.de>

Co-authored-by: scoder <stefan_ml@behnel.de>
This commit is contained in:
Miss Skeleton (bot) 2020-10-04 16:56:56 -07:00 committed by GitHub
parent 7aa22ba923
commit d5719247ba
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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