Python (and me) getting confused finding keys

Tim Golden mail at timgolden.me.uk
Tue Dec 22 11:45:36 EST 2009


John wrote:
> 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?

Three ways that I can think of. Doubtless there are more.

1) Mutating the dictionary within the loop:

edges = dict.fromkeys (range (10))
for e in edges.keys ():
  assert edges.has_key (e), "edges does not have %s" % e
  del edges[e + 1]


2) A race condition (sort of generalisation of (1)): 
some other thread removes something from edges during the iteration


3) edges isn't a dictionary but a dictalike structure which
doesn't do what you expect for .keys and .has_key.

TJG



More information about the Python-list mailing list