0

I understand that how * and ** operators generally work. In the following code [ taken from django's source ]

def curry(_curried_func, *args, **kwargs):
    def _curried(*moreargs, **morekwargs):
        return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
return _curried

I get how the args + moreargs part work - the [non - keyword ] arguments passed initially to the function curry and the arguments passed to the curried function returned by curry are combined. What I don't get is how the **dict(kwargs, **morekwargs) works. Could someone please explain that bit?

ersran9
  • 968
  • 1
  • 8
  • 13
  • 1
    Have you read this? http://stackoverflow.com/questions/2921847/python-once-and-for-all-what-does-the-star-operator-mean-in-python – Henrik Andersson Jun 27 '13 at 14:20
  • 1
    @limelights I read it just now. As I mentioned in my post, I understand [ hopefully :) ] how the `**` operator works. My doubt is with the `**dict(kwargs, **morekwargs)` part. – ersran9 Jun 27 '13 at 14:24
  • Yeah, i totally misread it, but left it for good FYI. Sorry about that! – Henrik Andersson Jun 27 '13 at 14:25

2 Answers2

2

dict(kwargs, **morekwargs) is a trick (that Guido dislikes) for combining 2 dictionaries into 1.

>>> d = {'foo':'bar'}
>>> kwargs = {'bar':'baz'}
>>> dict(d,**kwargs)
{'foo': 'bar', 'bar': 'baz'}

So, the curried function takes all kwargs passed to curry and adds them to the additional kwargs passed to the _curried function to create a super dictionary. that super dictionary gets unpacked and sent on to the _curried_func.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    Reference for the "Guido dislikes" part: http://mail.python.org/pipermail/python-dev/2010-April/099459.html – Aya Jun 27 '13 at 14:27
  • @Aya -- After re-reading that, maybe "dislikes" wasn't strong enough... :). Thanks for the reference. – mgilson Jun 27 '13 at 14:29
  • @mgilson Thank you, and personally I find dict.update method to be much more easier on the eyes :) – ersran9 Jun 27 '13 at 14:35
1

It effectively builds a union of two dicts, kwargs and morekwargs. Example:

>>> kwargs = {"ham": 1, "spam": 2}
>>> morekwargs = {"spam": 3, "eggs": 2}
>>> dict(kwargs, **morekwargs)
{'eggs': 2, 'ham': 1, 'spam': 3}

This works because the dict constructor takes keyword arguments, so it's the same as

>>> dict(kwargs, spam=3, eggs=2)
{'eggs': 2, 'ham': 1, 'spam': 3}

Finally, the resulting dict is fed as keyword arguments to _curried_func by means of **.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836