[ZODB-Dev] BTrees and setdefault

Tim Peters tim at zope.com
Fri Aug 26 11:17:07 EDT 2005


[Ruslan Spivak]
> I just read links sent by Dmitriy and see that people have different
> views about 'setdefault'.

Dmitry proposed, and I asked for use cases.

    http://mail.zope.org/pipermail/zodb-dev/2004-October/008044.html

explains why I doubt setdefault() would be added to the Python core today,
knowing what we know now, if it weren't there already.  Dieter Maurer,
Jeremy Hylton, and Christian Reis replied; none were keen on the idea.

> Though i already see in Z3ECM workflow repository code like this:
>
> try:
>     return self.__applications[key]
> except KeyError:
>     self.__applications[key] = PersistentList()
>     return self.__applications[key]
>
> where __applications is OOBTree.

There are several other ways they could have written it.  If you don't care
about creating a new PersistentList() every time (and you can't care about
that if you want to use setdefault()), then

    self.__applications.insert(key, PersistentList())
    return self.__applications[key]

is one way to do it.  "The usual" idiom using .get() is another way:

    result = self.__applications.get(key, None)
    if result is None:
        result = self.__applications[key] = PersistentList()
    return result

Despite that the message I linked to above was written last October, there
are still only about a dozen total uses of setdefault() in the Python core,
and there are still many more lines of code in the core implementing the
thing than there are lines of code using it.  I remain -0 on the idea (which
means it's OK by me, I just prefer not to bother).  Jim's +1 wipes out any
number of -0 votes ;-).



More information about the ZODB-Dev mailing list