1

Is there a dunder method which corresponds to using the dictionary unpacking opertator ** on an object?

For example:

class Foo():
    def __some_dunder__(self):
        return {'a': 1, 'b': 2}

foo = Foo()
assert {'a': 1, 'b': 2} == {**foo}
Austin
  • 299
  • 1
  • 17
  • It's not clear what you want. Are `a` and `b` the instance variables of `foo` or are they class variables? Where do those values come from? Or is that the hard coded dict you wanna throw out during unpacking? – Amit Singh May 30 '21 at 16:37
  • Dupe: https://stackoverflow.com/q/8601268/3001761 – jonrsharpe May 30 '21 at 16:58

1 Answers1

2

I've managed to satisfy the constraint with two methods (Python 3.9) __getitem__ and keys():

class Foo:
    def __getitem__(self, k): # <-- obviously, this is dummy implementation
        if k == "a":
            return 1

        if k == "b":
            return 2

    def keys(self):
        return ("a", "b")


foo = Foo()
assert {"a": 1, "b": 2} == {**foo}

For more complete solution you can subclass from collections.abc.Mapping (Needs implementing 3 methods __getitem__, __iter__, __len__)

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91