[Django]-Template View – kwargs and **kwargs

3πŸ‘

βœ…

In a function declaration, **kwargs will take all unspecified keyword arguments and convert them into a dictionary.

>>> test_dict = {'a':1, 'b':2}
>>> def test(**kwargs):
...     print (kwargs)
...
>>> test(**test_dict)
{'b': 2, 'a': 1}

Note that the dictionary object has to be converted using ** when it is passed to the function (test(**test_dict)) and when it is received by the function. It is impossible to do the following:

>>> test(test_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: test() takes 0 positional arguments but 1 was given

So, in your example, the first **kwargs unpacks the keyword arguments into a dictionary, and then the second packs them back up to be sent to the parent.

A function with **kwargs in the signature can either received an unpacked dictionary or unspecified keyword arguments. Here’s an example of the second case:

>>> def test(arg1, **kwargs):
...     print (kwargs)
...
>>> test('first', a=1, b=2)
{'b': 2, 'a': 1}
πŸ‘€brianpck

2πŸ‘

Here at your function definition, it is accepting multiple arguments, and parsing them into a dict. def get_context_data(self, **kwargs):

So now, kwargs is a dictionary object. So if you pass it to .get_context_data(kwargs) it would have to expect only a single incoming argument, and treat it as a dictionary.

So when you do **kwargs a second time, you are blowing up the dictionary back into keyword arguments that will expand into that functions call.

πŸ‘€CasualDemon

Leave a comment