[ZODB-Dev] BTree.setdefault(), BTree.pop()

Dmitry Vasiliev lists at hlabs.spb.ru
Mon Oct 4 12:11:20 EDT 2004


Tim Peters wrote:
> [Dmitry Vasiliev]
> 
>>I want to add .setdefault(key, default) (with mandatory 'default'
>>argument) and .pop(key, default) methods to BTrees so BTree interface
>>will be closer to Python 2.3 dictionaries interface.
>>
>>Any objections?
> 
> 
> I'd like to hear people say they're going to *use* these in the context of
> BTrees first.  Just piling on new methods for its own sake creates ongoing
> maintenance burdens without payback.  Offhand, neither of these methods make
> particularly good sense to me for the ways BTrees are used.  For example,
> the fundamental reason for dict.pop() to have a default in Python is to
> avoid the need for a critical section in multithreaded Python apps; but
> BTrees are very rarely used in apps where two threads may be mucking with
> the same in-memory BTree at the same time (note that two threads in ZODB
> mucking with the same *database* BTree at the same time is common, but
> because each thread has its own connection to the database these threads are
> nevertheless mucking with distinct in-memory BTrees).
> 
> BTW, part of .setdefault() *functionality* has been in BTrees from long
> before Python added it to dictionaries:
> 
> 
>>>>from BTrees.OOBTree import *
>>>>b = OOBTree([(1, 2)])
>>>>b.insert(1, 8)   # does not replace b[1], and returns false
> 
> 0
> 
>>>>list(b.items())
> 
> [(1, 2)]
> 
>>>>b.insert(2, 4)   # adds b[2], and returns true
> 
> 1
> 
>>>>list(b.items())
> 
> [(1, 2), (2, 4)]
> 
> The difference is that, "win or lose", .setdefault() returns the value
> associated with the key, but doesn't tell you whether you won or lost.
> insert() tells you whether you won or lost, but doesn't tell you the current
> value associated with the key.  The existence of insert() was driven by a
> specific use case, explained in the BTrees Interfaces.py.  Use cases should
> drive this.

Use case for .setdefault():

 >>> from BTrees.OOBTree import OOBTree
 >>> from persistent.list import PersistentList
 >>> t = OOBTree()
 >>> t.setdefault(key, PersistentList()).append(value)

-- 
Dmitry Vasiliev (dima at hlabs.spb.ru)
     http://hlabs.spb.ru


More information about the ZODB-Dev mailing list