Is there a way to implement the ** operator on a custom object
Alan Bawden
alan at csail.mit.edu
Fri Feb 9 01:26:16 EST 2024
Chris Angelico <rosuav at gmail.com> writes:
> On 08Feb2024 12:21, tony.flury at btinternet.com <tony.flury at btinternet.com> wrote:
> >I know that mappings by default support the ** operator, to unpack the
> >mapping into key word arguments.
> >
> >Has it been considered implementing a dunder method for the **
> >operator so you could unpack an object into a key word argument, and
> >the developer could choose which keywords would be generated (or could
> >even generate 'virtual' attributes).
I presume this is more like:
obj = SomeObject()
func(**obj)
ie making the object behave in a dict-like way. I can't remember how
this is implemented, but you can create the necessary methods to have
your object produce whatever it likes.
All you need to do is subclass collections.abc.Mapping, and
implement __len__, __iter__, and __getitem__. Pretty easy.
- Alan
More information about the Python-list
mailing list