Skip to content

Supporting __add__ in Dict #7

@Jean-Daniel

Description

@Jean-Daniel

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 ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions