5

From reading this example and from my slim knowledge of Python it must be a shortcut for converting an array to a dictionary or something?

class hello:
    def GET(self, name):
        return render.hello(name=name)
        # Another way:
        #return render.hello(**locals())
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Ryan Detzel
  • 5,519
  • 9
  • 37
  • 49
  • 1
    Actually this is not really a duplicate. This questions asks what calling a function with `f(**d)` means, while the other question seems to be more about `*` and `**` in function parameter definitions. – sth Apr 21 '11 at 15:10

4 Answers4

11

In python f(**d) passes the values in the dictionary d as keyword parameters to the function f. Similarly f(*a) passes the values from the array a as positional parameters.

As an example:

def f(count, msg):
  for i in range(count):
    print msg

Calling this function with **d or *a:

>>> d = {'count': 2, 'msg': "abc"}
>>> f(**d)
abc
abc
>>> a = [1, "xyz"]
>>> f(*a)
xyz
sth
  • 222,467
  • 53
  • 283
  • 367
1

It "unpacks" an dictionary as an argument list. ie:

def somefunction(keyword1, anotherkeyword):
   pass

it could be called as

somefunction(keyword1=something, anotherkeyword=something)
or as
di = {'keyword1' : 'something', anotherkeyword : 'something'}
somefunction(**di)
Silfverstrom
  • 28,292
  • 6
  • 45
  • 57
1

From the Python docuemntation, 5.3.4:

If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax **identifier is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.

This is also used for the power operator, in a different context.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
1

**local() passes the dictionary corresponding to the local namespace of the caller. When passing a function with ** a dictionary is passed, this allows variable length argument lists.