[Tutor] What does this mean

Jeremy Jones zanesdad at bellsouth.net
Sat Feb 12 03:39:46 CET 2005



jrlen balane wrote:

>what does (*args, **kwargs) mean??? i'm sort of a bit confused... thanks.
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
*args is notation for list of arguments.  **kwargs is notation for 
keyword arguments.  Here is an example:


#######################
In [1]: def foo(bar, *args, **kwargs):
   ...:     print "bar", bar
   ...:     print "args", args
   ...:     print "kwargs", kwargs
   ...:

In [2]: foo('1')
bar 1
args ()
kwargs {}

In [3]: foo('1', 1, 2, 3)
bar 1
args (1, 2, 3)
kwargs {}

In [4]: foo('1', 1, 2, 3, bam=1, baz=2, boo=3)
bar 1
args (1, 2, 3)
kwargs {'bam': 1, 'baz': 2, 'boo': 3}
#######################

In the definition (at prompt [1]), I only stated 3 arguments to pass in: 
bar, args, and kwargs. 

At prompt [2], I pass in a "1" string as my only argument, which gets 
assigned to "bar". 

At prompt [3], I pass in "1", 1, 2, 3.  "1" gets assigned to foo as in 
the previous example.  (1,2,3) gets assigned to args.  The *args 
notations says, "Assign any following arguments to the args variable." 

At prompt [4], I pass in the same thing as at [3], but pass in keyword 
arguments (bam=1, baz=2, boo=3).  Everything gets assigned as it did at 
[3] except kwargs is a dictionary with keys 'bam', 'baz', and 'boo' with 
respective values 1,2,3.  The **kwargs notations says, "Assign any 
subsequent keyword arguments to kwargs."

NOTE - you don't have to use *args and **kwargs.  You just have to use 
the * and **.


Jeremy Jones


More information about the Tutor mailing list