Python *args and **kwargs demystified

*args and **kwargs demystified

Having hard time understanding the *args and **kwargs magic variables in python? well, this article will just try to ease this a bit. In Fact, the concept is very simple though they look fearsome due to look alikeness with C/C++ pointer thingies. *args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. Variable number means you don’t know the quantity in advance. Lets see an example of *args:

def foo(arg, *args):
    print "first variable:{}".format(arg)
    count = 2 
    for item in args:
        print "variable no:{} => {}".format(count,item)
        count += 1


joy [chef_painting] $ python 
first variable:python
variable no:2 => is
variable no:3 => better
variable no:4 => than
variable no:5 => java

With **kwargs, we can actually send key, value pairs to python function.

def foo(**kwargs):
    count = 1
    if kwargs is not None:
        for k, v in kwargs.iteritems():
            print "#{} key:{} =>value:{}".format(count,k,v)
            count +=1


joy [chef_painting] $ python 
#1 key:lang => value:python
#2 key:version => value:2.7
#3 key:author => value:joy


মন্তব্য করুন

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

You are commenting using your account. Log Out /  পরিবর্তন )

Google+ photo

You are commenting using your Google+ account. Log Out /  পরিবর্তন )

Twitter picture

You are commenting using your Twitter account. Log Out /  পরিবর্তন )

Facebook photo

You are commenting using your Facebook account. Log Out /  পরিবর্তন )


Connecting to %s

%d bloggers like this: