09.10.21 01:24, Tyler Hou via Python-ideas пише: > Concretely, I'm proposing the following set of changes to Python: > > 1. If the size of a list, set, or dict changes, invalidate all existing > iterators to that containers. Document this behavior as part of the public > API. > 2. Attempting to call next() on an invalidated iterator raises a RuntimeError. > 3. Add a key_iter function to itertools (name up for debate), which > replicates the existing functionality for lists. It could also make a copy of > the keys of a set/dict, so you could use it to mutate those as well during > iteration (to allow users to write functions that mutate an arbitrary > duck-typed collection) > 4. Gate (1, 2) for lists behind a __future__ flag with a long migration > window (e.g. ~3.16).
I see two drawbacks: 1. It is a breaking change. I do not think there is much code which modify a list during iteration, but still. 2. It adds an overhead to iteration and mutating operations. And this is more severe drawback, because it affects a much of code. And the only argument for this change is consistency with set and dict. It is very weak argument, because list differs from set and dict in so many ways. Iteration of lists after mutating is deterministic and well predictable. This is why it can be used in code and no RuntimeError is raised. In contrary, iteration of sets and dicts after mutating is unpredicable. You can miss some items, get some items multiple times, and it depends on the history of set and dict, types and values of keys, and just be random. We try to detect this and raise RuntimeError because there is no way to use it correctly. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/CYU4J5IA56DK4VIDJBNUHBFPRCL2752G/ Code of Conduct: http://python.org/psf/codeofconduct/