PEP 234: Iterators

Michael Hudson mwh21 at cam.ac.uk
Tue May 1 11:35:17 EDT 2001


Toby Dickenson <tdickenson at devmail.geminidataloggers.co.uk> writes:

> What happens if you do violate this? I assume that damage is limited
> to seing elements twice, or skipping some elements and not seeing them
> at all.

You (probably) get an exception.  If you're really careful, you could
probably miss elements, and if you're really really careful you could
probably get it to hit elements twice (esp. if you do something dense
like classes whose __hash__ always returns 1, for example).

It's probably worrying that I can cook up things like:

->> d = {1:1, 2:2, 3:3, 4:4}
/>> for i in d:
|..     print d[i]
|..     if i == 4:
|..         d[9] = 5
\__ 
4
3
2
1
5
->> d = {1:1, 2:2, 3:3, 4:4}
/>> for i in d:
|..     print d[i]
|..     if i == 4:
|..         d[12] = 12
\__ 
4
3
2
1

Often, though, you'll get:

->> d = {1:1, 2:2}
/>> for i in d:
|..     print d[i]
|..     if i == 2:
|..         d[12] = 12
\__ 
2
Traceback (most recent call last):
  File "<input>", line 1, in ?
RuntimeError: dictionary changed size during iteration

basically-the-message-is-"don't-do-that"-ly y'rs
M.

-- 
  If you give someone Fortran, he has Fortran.
  If you give someone Lisp, he has any language he pleases.
    -- Guy L. Steele Jr, quoted by David Rush in comp.lang.scheme.scsh



More information about the Python-list mailing list