Use ** kwargs both when calling the function and in the definition

Suppose I have a get_data function that takes a number of keyword arguments. Is there any way to 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) 

Thus, the idea is to avoid entering argument names both in the function call and in the function definition. I call a function with a dictionary as an argument, and the dictionary keys become local variables of the function, and their values ​​are the dictionary values

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

So my code will 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 that won't work either. Also, I cannot achieve behavior without using locals() ?

+6
source share
2 answers

**kwargs is a simple dictionary. Try the following:

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

Also check the documentation for keyword arguments .

+11
source

If we look at your example:

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

There is a variable named arg1 in your get_data function namespace, but there is no variable named arg2 . therefore, you cannot reach a function or variable that is not in your namespace.

In fact, in your namespace; there is an arg1 variable and a dictionary object called kwargs . using the notation ** before kwargs (there is no kwargs value here, it could be something else.) tells your python compiler that kwargs is a dictionary, and all values ​​in this dictionary will be evaluated as named parameters in your function definition.

Let's look at this example:

 def myFunc(**kwargs): do something myFunc(key1='mykey', key2=2) 

when you call myFunc with the named parameters key1 and key2 , your function definition acts like

 def myFunc(key1=None, key2=None): 

but with the exception! since myFunc do not have named parameters, the compiler does not know how to handle them directly, since you can pass any named parameter to your function.

So, your function accepts these named parameters in the dictionary, as you call your function:

 myFunc({key1:'mykey', key2:2}) 

So your function definition gets these parameters in the dictionary. **kwargs defines your dictionary at this point, which also tells the compiler that any named parameters will be accepted (using the ** icons in front of kwargs)

 def myFunc(**kwargs): print kwargs 

will print

 {key1:'mykey', key2:2} 

So, in your example, you can use kwargs as a dictionary;

 def myFunc(**kwargs): kwargs['arg2'] kwargs.get('arg3') 

Hope this is not difficult (:

+3
source

Source: https://habr.com/ru/post/945161/


All Articles