1

I saw the following code:

def __init__(self, fn, **kw):
     [setattr(self,k,v) for (k,v) in kw.items()]
     ......

What does the input argument **kw mean?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Yan Zhu
  • 4,036
  • 3
  • 21
  • 37

4 Answers4

5

kw is bound to a dict mapping keyword argument names to their values.

Try calling

def return_kwargs(**kw):
    return kw

as return_kwargs(foo=1, bar="2", baz="hamspamspam").

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • So. Suppose the class's name is Foo. Then I can create it as: F=(Foo, a, b, c, d, e). Then kw == {b:c, d:e}??? – Yan Zhu Mar 09 '12 at 18:19
  • 1
    @YanZhu: no, because you (a) that doesn't create a `Foo` and (b) if you meant `Foo(a, b, c, d, e)`, that doesn't pass keyword arguments but the values `a` through `e`. Read the link I posted. – Fred Foo Mar 09 '12 at 18:30
1

Suppose you have a dict kw = {'a':1,'b':2}, then calling myfunction(**kw) is equivalent to calling myfunction(a=1,b=2).

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • This is the opposite of using `**kw` in the function declaration. The similarity is no accident, of course. – alexis Mar 09 '12 at 18:58
1

This particular construction means what all keyword arguments for the constructor will end up as object attributes.

foo = Foo( func, bar = 1, baz = "aa" )

this would create an object with attribute "bar" set to 1 and "baz" to "aa"

sigman
  • 1,291
  • 12
  • 13
  • You're right but he's only asking about the `**kw` part. The attribute magic is done by `setattr()`. – alexis Mar 09 '12 at 18:56
1

Inside the function, kw is a dictionary that contains all the keyword=value arguments that you gave to your function:

def demo(**kw):
    print kw

demo(a=1, b="hello")

Run the above and it will display a dictionary with two keys, a and b. So it works as a way to accept any keyword argument you decide to use when you call the function.

That's what it does. Why would anyone want to do that? Perhaps in a function that calls another function (given as a separate argument), and **kw is to hold options for the second function.

alexis
  • 48,685
  • 16
  • 101
  • 161