Python (and me) getting confused finding keys

Tim Golden mail at timgolden.me.uk
Tue Dec 22 12:07:17 EST 2009


John wrote:
>> another thread can remove the key prior to the has_key call; or perhaps
>>  edges isn't a real dictionary?
>>
> 
> of course. But unless there is a way of using threading without being aware of 
> it, this is not the case. Also, edges is definitely a dict (has been declared 
> some lines before, and no obscure functions have been called in the meantime, 
> just some adding to edges). Python would also fail on edges.keys() if edges 
> wasn't a dict...

Well of course you only showed us three lines of code which
means that all possibilities are open. And edges.keys () would certainly
be valid for something like this (random) class:


<code>

class Edges (object):
  def __init__ (self):
    self._keys = range (10)
  def keys (self):
    return [k * k for k in self._keys]
  def has_key (self, key):
    return False
  def __getitem__ (self, key):
    return self._keys.index (key)

edges = Edges ()

for e in edges.keys ():
  assert edges.has_key (e)

</code>


A bizarre example, certainly, but one which illustrates what
*might* be happening especially if you only show peephole
code.

TJG



More information about the Python-list mailing list