python, tutorial

*args and **kwargs in python explained

Hi there folks. I have come to see that most new python programmers have a hard time figuring out the *args and **kwargs magic variables. So what are they ? First of all let me tell you that it is not necessary to write *args or **kwargs. Only the * (aesteric) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention. So now lets take a look at *args first.

Usage of *args
*args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you do not know before hand that how many arguments can be passed to your function by the user so in this case you use these two keywords. *args is used to send a non-keyworded variable length argument list to the function. Here’s an example to help you get a clear idea:

def test_var_args(f_arg, *argv):
    print "first normal arg:", f_arg
    for arg in argv:
        print "another arg through *argv :", arg

test_var_args('yasoob','python','eggs','test')

This produces the following result:

first normal arg: yasoob
another arg through *argv : python
another arg through *argv : eggs
another arg through *argv : test

I hope this cleared away any confusion that you had. So now lets talk about **kwargs

Usage of **kwargs
**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. Here is an example to get you going with it:

def greet_me(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.iteritems():
            print "%s == %s" %(key,value)
 
>>> greet_me(name="yasoob")
name == yasoob

So can you see how we handled a keyworded argument list in our function. This is just the basics of **kwargs and you can see how useful it is. Now lets talk about how you can use *args and **kwargs to call a function with a list or dictionary of arguments.

Using *args and **kwargs to call a function
So here we will see how to call a function using *args and **kwargs. Just consider that you have this little function:

def test_args_kwargs(arg1, arg2, arg3):
    print "arg1:", arg1
    print "arg2:", arg2
    print "arg3:", arg3

Now you can use *args or **kwargs to pass arguments to this little function. Here’s how to do it:

# first with *args
>>> args = ("two", 3,5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5

# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3

Order of using *args **kwargs and formal args
So if you want to use all three of these in functions then the order is

some_func(fargs,*args,**kwargs)

I hope you have understood the usage of *args and **kwargs. If you have got any problems or confusions with this then feel free to comment below. For further study i suggest the official python docs on defining functions and *args and **kwargs on stackoverflow.

You might also like :
*) Making a url shortener in python
*) 20 Python libraries you can’t live without
*) Targeting python 2 and 3 at the same time.

Standard

24 thoughts on “*args and **kwargs in python explained

  1. Saw your links to this in the python programmers group on fb. I have been coding for a while now, but didn’t know anything about this. your blog is really really helpful! Thank’s for posting this, and keep the fb group updated with your posts!

    • Thanx i am glad that you found this helpful. If you want regular updates then consider following this blog. The link for following is available in the menu.

  2. Pingback: Python socket network programming | Bite Sized Python Tips

  3. Pingback: The self keyword in python explained | Bite Sized Python Tips

  4. Pingback: The self variable in python explained | Bite Sized Python Tips

  5. Pingback: Storing and Loading Data with JSON | Bite Sized Python Tips

  6. Pingback: Best Python Resources for Beginners and Professionals | Bite Sized Python Tips

  7. Pingback: Yasoob Khalid: Best Python Resources for Beginners and Professionals | The Black Velvet Room

  8. Per says:

    Hi im trying to use a fill_between command but i dont know what to put in the **kwargs “section”.

    This is my coding:

    (…)

    fill_between(x, y1, y2=0, where=None, **kwargs)

    What should i write in the kwargs** section?

    Greetings from Norway.

    • Hi Per. Welcome to my blog. Now regarding your problem I am sorry that I am not able to clearly understand you. What you can do is that you can write a detailed email to me or use stackoverflow :) In both cases you will get help.

  9. Pingback: Naudingos python nuorodos

  10. Juan Sierra Pons says:

    Quick and easy.
    Still learning python from a book and I didn’t find anything on it reletated to to *args
    and *kwargs
    Thanks for sharing your knowlegde and time.

  11. hi really it’s I needed, I searched a lot finally I found and I understand *args and **kwargs. can you please in the same way explain django views modesls program and urls patterens mapping.thank you very much.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s