How does one implement custom double star operator (**
) for unpacking, similar to how __iter__
works with single star operator (*
)?
As @ShadowRanger says, implement Mapping. Here's an example:
from collections.abc import Mapping
class Foo(Mapping):
def __iter__(self):
yield "a"
yield "b"
def __len__(self):
return 2
def __getitem__(self, item):
return ord(item)
f = Foo()
print(*f)
print(dict(**f))
The program outputs:
a b
{'a': 97, 'b': 98}