pythondictionaryargument-unpacking

Is Python dictionary unpacking customizable?


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}

Solution

  • 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__)