Python (and me) getting confused finding keys

Christian Heimes lists at cheimes.de
Tue Dec 22 11:47:14 EST 2009


John schrieb:
> Hi there,
> 
> I have a rather lengthy program that troubles me for quite some time. After 
> some debugging, I arrived at the following assertion error:
> 
> for e in edges.keys():
> 	assert edges.has_key(e)
> 
> Oops!? Is there ANY way that something like this can possibly happen?

Yes, it happens when another part of your program -- most likely a
thread -- modifies edges while you are iterating over its keys. The
keys() method of a dict returns a *copy* of its keys. If you had uses
"for e in edges" you'd have seen a RuntimeError "dictionary changed size
during iteration". With keys() you see the snapshot of edges's keys when
keys() is called.

Christian

PS: Use "e in edges" instead of "edges.has_key(e)". It's faster.




More information about the Python-list mailing list