[Tutor] Need better understanding of **kwargs

Mark Tolonen metolone+gmane at gmail.com
Sat Jun 6 20:25:27 CEST 2009


"Eduardo Vieira" <eduardo.susan at gmail.com> wrote in message 
news:9356b9f30906061044i4ded250fif3b387e64a11700d at mail.gmail.com...
> Hello, I thought I understood **kwargs until I stumbled with this 
> function:
>
> def changeflexion(myword, mytag, **dicty):
>    global er_verbs
>    global ar_verbs
>    global ir_verbs
> #    global dicty
>    for item in dicty:
>        if myword in item and mytag in item[1]:
>            if dicty[item].endswith('ar'):
>                ending = item[0].replace(dicty[item][:-2], "")
>                try:
>                    return dicty[item][:-2] + ar_verbs[ending]
>                except KeyError:
>                    return item[0]
>            elif dicty[item].endswith('er'):
>                ending = item[0].replace(dicty[item][:-2], "")
>                try:
>                    return dicty[item][:-2] + er_verbs[ending]
>                except KeyError:
>                    return item[0]
>            elif dicty[item].endswith('ir'):
>                ending = item[0].replace(dicty[item][:-2], "")
>                try:
>                    return dicty[item][:-2] + ir_verbs[ending]
>                except KeyError:
>                    return item[0]
>            else:
>                return item[0]
>
> but when I import the module and call:
> a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict)
> I get this error:
> TypeError: changeflexion() takes exactly 2 arguments (3 given)
> Isn't the 3rd argument supposed to be a dictionary?

No, **dicty means the function takes zero or more keyword parameters:

>>> def f(a,b,**k):
...  print a,b,k
...
>>> f(1,2) # no keyword parameters
1 2 {}
>>> f(1,2,c=3) # one keyword parameter
1 2 {'c': 3}
>>> f(1,2,{'c':3}) # a dictionary
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: f() takes exactly 2 arguments (3 given)

But there is a syntax to pass keyword arguments as a dictionary:

>>> f(1,2,**{'c':3})
1 2 {'c': 3}

-Mark




More information about the Tutor mailing list