Which objects are expanded by double-star ** operator?

Ian Kelly ian.g.kelly at gmail.com
Mon Jun 7 17:04:35 EDT 2010


On Mon, Jun 7, 2010 at 2:17 PM, kkumer
<kkumer at best-search-engines-mail.com> wrote:
>
> I have to merge two dictionaries into one, and in
> a "shallow" way: changing items should be possible
> by operating either on two parents or on a
> new dictionary. I am open to suggestions how
> to do this (values are always numbers, BTW), but
> I tried to do it by creating a dict-like class that just
> forwards all calls to the two parent dicts, see below.
>
> It works, but one important thing is missing. I
> am not able to expand new dictionary with
> double-star operator ** to use it as a
> set of keyword arguments of a function.
> I googled a bit, but was unable to find what
> property must an object have to be correctly
> treated by **.

I don't think that what you want to do here is possible.  It appears
to be hard-coded and not affected by subclassing, as evidenced by the
following snippet:

class NonDict(dict):
    for attr in dict.__dict__:
        if attr not in ('__init__', '__new__',):
            locals()[attr] = None

d = NonDict({'a': 1})
def kwa(**kw): print kw
kwa(**d)

Prints:
{'a': 1}

Cheers,
Ian



More information about the Python-list mailing list