]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-41892: Clarify that an example in the ElementTree docs explicitly avoids modifyin...
authorscoder <stefan_ml@behnel.de>
Sun, 4 Oct 2020 23:13:46 +0000 (01:13 +0200)
committerGitHub <noreply@github.com>
Sun, 4 Oct 2020 23:13:46 +0000 (19:13 -0400)
Doc/library/xml.etree.elementtree.rst

index 7725e4d158d429e90be266ef91450bec628f2f11..f4bccf6609810ee05814d0ce5a0eac1654f197f5 100644 (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