[Tutor] understanding **kwargs syntax

Alan Gauld alan.gauld at btinternet.com
Thu Aug 25 10:44:55 CEST 2011


On 25/08/11 09:27, John wrote:
> Just a quick question,
>
> is it wrong to use the *args and **kwargs ( the latter in particular)
> when DEFINING a function?

No, in fact it's essential if you don't know in advance what arguments 
are going to be passed to the function. This is very common if you are 
wrapping another function that itself takes variable arguments.

> def fest(**kwargs):
>      """ a function test """
>      keys = sorted(kwargs.keys())
>
>      print("You provided {0} keywords::\n".format(len(keys)))
>      for kw in keys:
>          print("{0} =>  {1}".format(kw, kwargs[kw]))
>
> Are there some good examples of when this would be a good idea to implement?

GUI frameworks like Tkinter often take variable numbers of configuration 
values. If you want to wrap that with a
function of your own you can do something like(pseudocode):

def myfunc(**kwargs):
    if some interesting arg exists
         do something with it
    return wrappedFunc(kwargs)

There are plenty other cases, try grepping the standard library code
for lines with def and **kwargs for some examples...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list