5

Possible Duplicate:
What does *args and **kwargs mean?

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())
Community
  • 1
  • 1
Ryan Detzel
  • 5,420
  • 8
  • 36
  • 47
  • exact duplicate http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean – SilentGhost Jul 24 '09 at 18:05
  • 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
  • 211,504
  • 50
  • 270
  • 362
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
  • 26,646
  • 6
  • 44
  • 56
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
  • 539,124
  • 75
  • 1,126
  • 1,354
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.