Python 字典解包是否可以自定义?

Is Python dictionary unpacking customizable?

是否有对应于在对象上使用字典解包运算符 ** 的 dunder 方法?

例如:

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

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

我已经设法用两种方法满足约束条件 (Python 3.9) __getitem__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}

要获得更完整的解决方案,您可以从 collections.abc.Mapping 继承(需要实现 3 种方法 __getitem____iter____len__