[Python-3000] A request to keep dict.setdefault() in 3.0

Guido van Rossum guido at python.org
Mon Jul 9 23:04:56 CEST 2007


On 7/9/07, Barry Warsaw <barry at python.org> wrote:
> Phillip, I support any initiative to keep .setdefault() or similar
> functionality.  When this thread came up before, I wasn't against
> defaultdict, I just didn't think it covered enough of the use cases
> of .setdefault() to warrant its removal.  You describe some
> additional use cases.
>
> However, .setdefault() is a horrible name because it's not clear from
> the name that a 'get' operation also happens.

We had a long name discussion when it was introduced. Perhaps we can
go back to the list suggested then and see if a better alternative was
overlooked?

> It occurs to me that I haven't reached my stupid idea quota for the
> day, so here goes.  What if we ditched .setdefault() as a name and
> gave .get() an optional argument to also set the key's value when
> it's missing.
>
[...]
>      def get(self, key, default=None, set_missing=False):
>          missing = object()
>          value = super(dict2, self).get(key, missing)
>          if value is not missing:
>              return value
>          if set_missing:
>              self[key] = default
>          return default
>
> This more or less conveys that both a get and a set operation is
> happening.  It also doesn't violate the rule against letting an
> argument change the return type of a function.  Maybe it will make
> this useful functionality more palatable.

But it does violate the rule that if you have a boolean flag to
indicate a "variant" of an API and in practice you'll always be
passing a constant for that flag, you're better off defining two
methods with different names. Although if the return type isn't
different, the semantics are certainly *very* different here. So I'm
strongly against this.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list