kadet
kadet copied to clipboard
Supporting __add__ in Dict
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 ?
I think that's a great idea as it removes the need to check if it exists, etc...