Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use **kwargs both in function calling and definition

Tags:

python

Suppose I have a function get_data which takes some number of keyword arguments. Is there some way I can do this

def get_data(arg1, **kwargs):
    print arg1, arg2, arg3, arg4

arg1 = 1
data['arg2'] = 2 
data['arg3'] = 3 
data['arg4'] = 4 

get_data(arg1, **data)

So the idea is to avoid typing the argument names in both function calling and function definition. I call the function with a dictionary as argument and the keys of the dictionary become local variables of function and their values are the dictionary values

I tried the above and got error saying global name 'arg2' is not defined. I understand I can change the locals() in the definition of get_data to get the desired behavior.

So my code would look like this

def get_data(arg1, kwargs):
    locals().update(kwargs)
    print arg1, arg2, arg3, arg4

arg1 = 1
data['arg2'] = 2 
data['arg3'] = 3 
data['arg4'] = 4 

get_data(arg1, data)

and it wouldn't work too. Also cant I achieve the behavior without using locals()?

like image 373
lovesh Avatar asked May 16 '13 12:05

lovesh


1 Answers

**kwargs is a plain dictionary. Try this:

def get_data(arg1, **kwargs):
    print arg1, kwargs['arg2'], kwargs['arg3'], kwargs['arg4']

Also, check documentation on keyword arguments.

like image 136
Vladimir Avatar answered Sep 21 '22 19:09

Vladimir