0

I see the discussion here setdefault vs. get and here when using setdefault (vs. defaultdict).

My question is more about coding style.

It's agreed that we shouldn't use setdefault for simple dict setting:

d = {}
d[k] = v

but not:

d.setdefault(k, v)

(using setdefault hints that k might be already in d and we doesn't want to override it)

As mention in the links above - we also use setdefault when want to get reference to the dict key's value (and use it)

d.setdefault(k, []).append(v)

Now, this is my case:

self._container["abc"] = self._object_handler.add(MyObject(*params))
instance = self._container["abc"]
instance.set_bla()
<more setting>

I need to do so several times so I would like to do all in one line. Since I think it's not readable to assign twice in one line:

instance = self._container["abc"] = self._object_handler.add(MyObject(*params))

I think that using setdefault is better:

instance = self._container.setdefault("abc", self._object_handler.add(MyObject(*params)))

What do you say - is it also use case for setdefault?

Community
  • 1
  • 1
alikyos
  • 86
  • 1
  • 7

0 Answers0