-1

I was just testing a piece of code with kwargs and args. But why args is picking up all the passed parameters in the following code ?

def myfunc(color='red',*args,**kwargs):
    print (args)
    print (color) 
    print (kwargs)
names=["Ramesh","Krishna"]
ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}

myfunc('blue',names,ages)

Result:

(['Ramesh', 'Krishna'], {'Krishna_age': 10, 'Ramesh_age': 20, 'Kanchi_age': 5})
blue
{}

why it all including ages has been assigned to ages and kwargs is empty ?

Webair
  • 95
  • 1
  • 6

3 Answers3

2

You need to use *names to unwrap names and **ages to unwrap ages.

Like this myfunc('blue', *names, **ages)

2

To be precise, kwargs is not picking up any values because kwargs looks for key - value pairs.

The way you passed your arguements, there is no key value pairs. You passed along

ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}

as a whole object, instead of destructuring the object and passing it as individual key value pairs.

As others have pointed out, the correct way is to destructure the object as seperate key value pairs as:

**ages
alex067
  • 3,159
  • 1
  • 11
  • 17
0

args looks for any values and kwargs looks for any key-value pairs. When you call your function, you have to specify * before args and ** before kwargs. It is the way Python works.

Here's your code:

def myfunc(color='red',*args,**kwargs):
    print (args)
    print (color) 
    print (kwargs)

names=["Ramesh","Krishna"]
ages={'Ramesh_age':20,'Krishna_age':10,'Kanchi_age':5}

# to call the function
myfunc('blue', *names, **ages)

Here's the results:

('Ramesh', 'Krishna')
blue
{'Ramesh_age': 20, 'Krishna_age': 10, 'Kanchi_age': 5}

Explanations can be found here and here

codrelphi
  • 1,075
  • 1
  • 7
  • 13