Monday, November 23, 2015

Understanding *args and **kwargs in Python

I need some time figuring out what is behind *args and **kwargs. Finally I understand it, so I want to share it with you here.

First of all, you need to know that what you need to understand here is the asterix (*), not the "args" and "kwargs". So if you write f(*params, **oparams) and f(*args, **kwargs), they both will behave similarly.

* is used to pass varied length of arguments. Here is an example on how to use *
def test_args(a, *b):

 def test_args(a, *b):  
   print "normal variable: ", a  
   print "first argument: ", b[0]  
   print "second argument: ", b[1]  
   print "third argument: ", b[2]  
 test_args('arwan', 1,2,3,4,5)  

From the example, "a" is single variable while "b" is varied length of argument. Thus, the first argument will be passed to "a" where the next variable will be passed to "b". Thus, all arguments (1,2,3,4,5) will be passed to "b" while only "arwan" will be passed to "a".

Double asterix (**) is used for varied argument with key. Here is an example.


 def test_args(a, **c):  
   print "normal variable: ", a  
   print "first argument: ", c['one']  
   print "second argument: ", c['two']  
   print "third argument: ", c['three']  
 test_args('arwan', one=1, two=2, three=3)  

In this example, the first argument is passed to "a", while next variable will be passed to "c".  Please notice that the way we pass the variable is different with single asterix(*). For two asterix (**), we need to define key for each value we pass. Note that the key is "one", "two" and "three" while the values are everything after "=".  The number of argument passed may be varied.

To make everything even more clear, here is another example to combine both.

 def test_args(a, *b, **c):  
   print "normal variable: ", a  
   print "arg 0: ", b[0]
   print "arg 1: ", b[1]
   print "arg 2: ", b[2]
   print "first argument: ", c['one']  
   print "second argument: ", c['two']  
   print "third argument: ", c['three']  
 test_args('arwan', 1, 2, 3, 4, one=1, two=2, three=3)  

No comments: