Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supporting __add__ in Dict #7

Open
Jean-Daniel opened this issue Mar 10, 2021 · 1 comment
Open

Supporting __add__ in Dict #7

Jean-Daniel opened this issue Mar 10, 2021 · 1 comment

Comments

@Jean-Daniel
Copy link

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 ?

@ramaro
Copy link
Member

ramaro commented Mar 11, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants