kadet icon indicating copy to clipboard operation
kadet copied to clipboard

Supporting __add__ in Dict

Open Jean-Daniel opened this issue 4 years ago • 1 comments

A common pattern in the Kubernetes generator is to create and populate arrays using the += operator on Dict.

item.root.volumeMounts += [value]

It works because the addict Dict implementation override __add__ to return the passed value if the Dict is empty (and raise an error otherwise).

    def __add__(self, other):
        if not self.keys():
            return other
        else:
            self_type = type(self).__name__
            other_type = type(other).__name__
            msg = "unsupported operand type(s) for +: '{}' and '{}'"
            raise TypeError(msg.format(self_type, other_type))

Which means this previous snippet will :

  • on first call, create a Dict because volumeMounts is not defined, and immediately replace this dict by [value].
  • on subsequent calls, append [value] to the array created on first call.

Should this package support this too ?

Jean-Daniel avatar Mar 10 '21 22:03 Jean-Daniel

I think that's a great idea as it removes the need to check if it exists, etc...

ramaro avatar Mar 11 '21 13:03 ramaro