durusmail: durus-users: del btree[key] ?
del btree[key] ?
2005-07-11
del btree[key] ?
Patrick K. O'Brien
2005-07-11
Mario Ruggier wrote:
> Hi,
>
> deleting items in a btree behaves surprisingly, when the key is complex.
> Here is a little sequence of commands that shows what I mean. Why isn't
> that one remaining item not deleted?

Because mutating a BTree while iterating its keys is a no-no.

[snip]

>>>>for key in b: del b[key]
>
> ....
>
>>>>b.items()
>
> [((<__main__.Test object at 0xc4b10>, <__main__.Test object at 0xc4ad0>,
> 'ssss', <__main__.Test object at 0xc4a90>), <__main__.Test object at
> 0xc4ff0>)]

Here is what you really want:

>>> from durus.btree import BTree
>>> b = BTree()
>>> b.add(1234, BTree)
>>> b.items()
[(1234, )]
>>> class Test(object): pass
....
>>> b[(Test(),Test(),'ssss',Test())] = Test()
>>> b.items()
[(1234, ), ((<__main__.Test object at
0x017FFFD0>, <__main__.Test object at 0x017FFFF0>, 'ssss',
<__main__.Test object at 0x018070F0>), <__main__.Test object at
0x017FFEF0>)]
>>> for key in b.keys(): del b[key]
....
>>> b.items()
[]
>>>

Note the difference in "for key in b" and "for key in b.keys()" is that
the latter creates a new list of keys that is independent from the
BTree, whereas the former makes use of iterkeys(), I believe.

--
Patrick K. O'Brien
Orbtech    http://www.orbtech.com
Schevo     http://www.schevo.org
Pypersyst  http://www.pypersyst.org

reply