varad
varad

Reputation: 8029

python call a function with kwargs

I have a function:

def myfunc():
    kwargs = {}
    a = 1
    b = 2
    kwargs.update(a=a, b=b)
    newfunc(**kwargs)

and my newfunc

def newfunc(**kwargs):
    print a

Its not giving the value of a which is 1

whats wrong ?

Upvotes: 4

Views: 8628

Answers (4)

Luc DUZAN
Luc DUZAN

Reputation: 1319

It's because you didn't put any key, value in your dictionary, you should have written that :

def newfunc(**kwargs):
    print kwargs["a"]

def myfunc():
    kwargs = {"a" :1, "b": 2}
    newfunc(**kwargs)

You can refer to this thread to understand kwargs better : Understanding kwargs in Python

Upvotes: 6

Marcus Müller
Marcus Müller

Reputation: 36337

You forgot to include the error. The Error would have been a NameError, a being undefined.

There's multiple things wrong with your code:

def myfunc():
    kwargs = {}
    a = 1
    b = 2

this doesn't change the dictionary kwargs. This just created two new local names a and b. I guess what you wanted to have is:

    kwargs = {}
    kwargs["a"] = 1
    kwargs["b"] = 2

EDIT: Your update does solve the issue above this line


Then:

def newfunc(**kwargs):
    print a

Will give you an Error, because where should a come from?

Using **kwargs here just tells python to store all (not previously absorbed) arguments get stored in a new dictionary. What you hence want is either something like:

def newfunc(a,b):
    print a

or

def newfunc(**kwargs):
    print kwargs["a"]

Taking a look at your code, you seem to struggle with the concepts of how to deal with dictionaries. Maybe the question you're asking would be easier for you to answer yourself if your sat back and read a tutorial on python's dict

Upvotes: 1

wagnerpeer
wagnerpeer

Reputation: 947

You should add yor variables to your dictionary and print the item at position of the variable. To me it looks like your code should be written as:

def myfunc():
    kwargs = {'a': 1,
              'b': 2}
    newfunc(**kwargs)

def newfunc(**kwargs):
    print(kwargs['a'])

if(__name__ == '__main__'):
    myfunc()

or your newfunc should have the arguments you want to fill with your kwargs dictionary like:

def myfunc():
    kwargs = {'a': 1,
              'b': 2}
    newfunc(**kwargs)

def newfunc(a, b):
    print(a)

if(__name__ == '__main__'):
    myfunc()

Hope that helps.

Upvotes: 2

301_Moved_Permanently
301_Moved_Permanently

Reputation: 4186

Two things.

First, your kwargs argument in myfunc is an empty dict, so you won't pass any parameters. If you want to pass the value of a and b to newfunc, you can either use

kwargs = {'a':1, 'b':2}
newfunc(**kwargs)

or

newfunc(a=1, b=2)

In both cases, you will get 'a' and 'b' in the kwargs dict of the newfunc function.

Second, you should extract your argument from the kwargs dict in newfunc. Something like print kwargs.get('a') should suffice.

Upvotes: 0

Related Questions