[Python-Dev] setdefault's second argument

Josiah Carlson jcarlson at uci.edu
Tue Aug 30 18:26:10 CEST 2005


Tim Peters <tim.peters at gmail.com> wrote:
> 
> Anyone remember why setdefault's second argument is optional?
> 
> >>> d = {}
> >>> d.setdefault(666)
> >>> d
> {666: None}

For quick reference for other people,  d.setdefault(key [, value])
returns the value that is currently there, or just assigned.  The only
case where it makes sense to omit the value parameter is in the case
where value=None.

> just doesn't seem useful.  In fact, it's so silly that someone calling
> setdefault with just one arg seems far more likely to have a bug in
> their code than to get an outcome they actually wanted.  Haven't found
> any 1-arg uses of setdefault() either, except for test code verifying
> that you _can_ omit the second arg.
> 
> This came up in ZODB-land, where someone volunteered to add
> setdefault() to BTrees.  Some flavors of BTrees are specialized to
> hold integer or float values, and then setting None as a value is
> impossible.  I resolved it there by making BTree.setdefault() require
> both arguments.  It was a surprise to me that dict.setdefault() didn't
> also require both.
> 
> If there isn't a sane use case for leaving the second argument out,
> I'd like to drop the possibility in P3K (assuming setdefault()
> survives).

I agree, at least that in the case where people actually want None (the
only time where the second argument is really optional, I think that
they should have to specify it.  EIBTI and all that.

 - Josiah



More information about the Python-Dev mailing list