*args and **kwargs

Manuel M. Garcia mgarcia at cole-switches.com
Tue Nov 26 20:26:33 EST 2002


On Wed, 27 Nov 2002 00:56:58 GMT, "Dan" <dan at cox.com> wrote:
(edit)
>Re: *args and **kwargs
>I am still pretty new on Python and have been working with it for 5 months.
>I ran across some source code that has these constructs.

These are one of the coolest things in Python!  In version 2 they
added these as the way to both allow arbitrary arguments to a function
and also apply a list and/or dictionary as arguments to a given
function.  (before you had to use the built-in function "apply" to do
this)

The names args and kwargs don't matter, you can call them anything you
wish.  (they stand for "arguments" and "keyword arguments")

Manuel

def f(*args, **kwargs):
    print 'args %r, kwargs %r' % (args, kwargs)

f(1,2,3,apple=4,orange=5)

def g(a, b, c, lemon=None, grape=None):
    print 'a %r, b %r, c %r, lemon %r, grape %r' % (a, b, c, lemon,
grape)

args = [6,7,8]
kwargs = {'lemon':9, 'grape':10}

f(*args, **kwargs)
g(*args, **kwargs)



More information about the Python-list mailing list