Re: Modify dict/set during iteration?



On 10月30日, 上午11时59分, Steven D'Aprano <st...@REMOVE-THIS-
cybersource.com.au> wrote:
On Thu, 29 Oct 2009 19:02:01 -0700, metal wrote:
I used this quickndirty way, any good idea to solve this problem?

It's not a problem that wants solving, it's a feature that wants paying
attention to.

As a general rule, you shouldn't modify data structures while you're
iterating over them, unless the data structure is advertised as safe to
modify while being iterated over, or you can do so in a way that is
guaranteed to be safe. When it comes to dicts and sets, neither of those
conditions hold.

Why do you want to do this? It seems like a lot of effort to avoid a
simple, straight-forward idiom:

make a copy of the dict or set
iterate over the copy, making changes to the original

What are you trying to accomplish by modifying objects while iterating
over them?



def miter(iterable):
[...]
        except RuntimeError, e:
            # Not sure if there were any other RuntimeError
            if 'changed size during iteration' in e.message:
                continue

That is not safe. There's no guarantee that the error message won't
change, even between one minor version to another, or between one Python
implementation and another. If you insist on making such an unsafe test,
at the very least be as conservative in what you expect as possible:

if 'changed' in e.message and 'size' in e.message:

and hope that nobody runs your code with internationalised error messages..

--
Steven

Yes the idoim rulz. I confused my self.

Maybe my real goal is the following:

def miter(iterable):
for x in tuple(iterable):
if x in iterable:
yield x

.



Relevant Pages

  • Re: Modify dict/set during iteration?
    ... you shouldn't modify data structures while you're ... What are you trying to accomplish by modifying objects while iterating ... As someone else pointed out, you can't use 'in' on a generator, for example. ...
    (comp.lang.python)
  • Re: Modify dict/set during iteration?
    ... you shouldn't modify data structures while you're ... guaranteed to be safe. ... What are you trying to accomplish by modifying objects while iterating ...
    (comp.lang.python)
  • modifying mutable list elements in a for loop
    ... The python tutorial tells me "It is not safe to modify the sequence ... [It seems to me that the list elements are pointers, ...
    (comp.lang.python)
  • Re: How to turn ON Regedit (so I can DELETE an entry)
    ... make sure this is not a spyware key. ... in safe made and then use regedit. ... > permissions to modify or delete the key. ...
    (microsoft.public.windowsxp.general)
  • Re: One More Power-Steering related Question
    ... Are there any LEGAL and SAFE ways to modify any conventional hydraulic ... PS system to reduce the amount of assist it generates, ... As in all driveability changes, ...
    (rec.autos.tech)