Search

04 April, 2019

How and when to use *args and **kwargs in Python

args and kwargs are special arguments (the words itself are just convention) which can be passed to a function.


Looks like this :

    def my_fun(*args):
        statements

Example of args:  


>>> def fun(*args):
 for item in args:
  print item

  
>>> fun(5,4,2)
5
4
2

This gives us ideas of how we can exploit this behavior.

If we do not not how many arguments we might pass, then using *args is a good idea.

Example of kwargs:



>>> def fun(**kwargs):
 for key, value in kwargs.iteritems(): # For Py3, use kwargs.items()
  print key, value

>>> fun(name='Arc', age=37)
age 37
name Arc

Obvious advantage is, if we don't know what arguments we might need in a function, we can use kwargs.

def foo(a, b, **kwargs):
    print....


Some Rules need to be followed to use them:


1. Either args or kwargs can exist independently
2. Names can be anything
3. There cannot be more than one ** or * element
4. Dictionary elements should be passed using = sign or using **

No comments:

Post a Comment