Is there a way to implement the ** operator on a custom object

Roel Schroeven roel at roelschroeven.net
Fri Feb 9 12:03:04 EST 2024


Left Right via Python-list schreef op 9/02/2024 om 17:09:
> In order for the "splat" operator to work, the type of the object must
> populate slot `tp_as_mapping` with a struct of this type:
> https://docs.python.org/3/c-api/typeobj.html#c.PyMappingMethods and
> have some non-null implementations of the methods this struct is
> supposed to contain.
>
> I can do this in C, but I cannot think of a way to do this in Python
> proper.

Looks like it can simply be done in Python, no tp_as_mapping needed. I 
tried it like Alan Bawden suggested (sibling post of yours):

import random # just as an example
import time   # just as an example
from collections.abc import Mapping

class VirtualKwargs(Mapping):

     def __init__(self):
         self.fncs = {
             # Simple examples of functions with varying return values to be
             # called for each lookup, instead of fixed values.
             'time': time.time,
             'random': random.random,
         }

     def __len__(self):
         return len(self.fncs)

     def __iter__(self):
         return iter(self.fncs)

     def __getitem__(self, key):
         return self.fncs[key]()


def func(**kwargs):
     for k, v in kwargs.items():
         print(f'{k}: {v}')


obj = VirtualKwargs()
func(**obj)


Output (obviously changes every run):

time: 1707497521.175763
random: 0.6765831287385126

-- 

"Man had always assumed that he was more intelligent than dolphins because
he had achieved so much — the wheel, New York, wars and so on — whilst all
the dolphins had ever done was muck about in the water having a good time.
But conversely, the dolphins had always believed that they were far more
intelligent than man — for precisely the same reasons."
         -- Douglas Adams



More information about the Python-list mailing list