]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifyin...
authorMiss Skeleton (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 4 Oct 2020 23:23:43 +0000 (16:23 -0700)
committerGitHub <noreply@github.com>
Sun, 4 Oct 2020 23:23:43 +0000 (16:23 -0700)
(cherry picked from commit 40db798692ca783fc2163656f196ac77e8b9e792)

Co-authored-by: scoder <stefan_ml@behnel.de>
Doc/library/xml.etree.elementtree.rst

index 44ac52aa83079aa575cbd36200bec6b1231f62e9..e4aedd1f9f08237dea5f1e6ab3dc4925d7a606f5 100644 (file)
@@ -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