[Python-Dev] setdefault's second argument

Tim Peters tim.peters at gmail.com
Tue Aug 30 18:38:55 CEST 2005

[Tim Peters]
>> Anyone remember why setdefault's second argument is optional?
>> >>> d = {}
>> >>> d.setdefault(666)
>> >>> d
>> {666: None}
>> ...
[Josiah Carlson]
> 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.

Yes, that's right.  Overwhelmingly most often in the wild, a
just-constructed empty container object is passed as the second
argument.  Rarely, I see 0 passed.  I've found no case where None is
wanted (except in the test suite, verifying that the 1-argument form
does indeed default to using None).

> ...
> 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.

And since there apparently aren't any such cases outside of Python's
test suite, that wouldn't be much of a burden on them <wink>.

More information about the Python-Dev mailing list