[Tutor] How to better understand args and kwargs

Alan Gauld alan.gauld at yahoo.co.uk
Sat Jul 24 14:34:58 EDT 2021


On 24/07/2021 15:43, Bhaskar Jha wrote:
> I am a newbie with Python. And, I want to understand what's the use of args
> and kwargs.. i understand that these are used when we do not know the
> number of arguments that will be passed.. but how is args different from
> kwargs.. 

args is for fixed arguments, kwargs is for arguments
specified using keywords.

def a(*args):
   for arg in args:
       print(arg)

def b(**kwargs):
   for nm,val in **kwargs.items():
      print(nm,':',val)

a(1,2,3) # use positional args

b(a=4,b=5,c=6) # use keyword args

def f(*args,**kwargs):
    for a in args:
       print(a,)
    for nm,val in kwargs.items():
       print(nm,':',val)

f(1,2,x=22,c="foo")  # use combination of positional and keyword


> and, why do we allow for a situation when someone can pass
> unlimited arguments to a function..

As for practical uses, one common example is a function
like print() which can take any number of arguments.

Another common use-case is where you are writing a function
that wraps another (possibly more complex) function and
simply passes through the values given along with some
hard coded choices. The user can pass in whatever values
they want to pass to the underlying function without
the wrapper having to understand all of them itself.

It isn't a common scenario but it does crop up quite
often in real world projects.

> other languages such as C++ do not make
> provisions for this. So, why does Python do it?

Many languages do, including C, C++ and C#

Here is the link for C++:

https://en.cppreference.com/w/cpp/language/variadic_arguments

But it tends to be a rare scenario so you don't her it
discussed very often.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list