15

What are Kwarg!!??

I have been going through a tutorial in django, trying to learn the language, and I stumbled on this.

I would really appreciate if some can post / point to a simple example that would help grasp why and how this is used.

Imran
  • 87,203
  • 23
  • 98
  • 131
Nelson_Wu
  • 161
  • 1
  • 1
  • 4
  • 4
    The language is not "Django". The language is Python. – Daniel Roseman Mar 10 '11 at 06:01
  • 1
    possible duplicate of [What does \*\* (double star) and \* (star) do for Python parameters?](http://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-python-parameters) – Mp0int Jul 24 '14 at 13:42
  • See the similar question [#3394835](http://stackoverflow.com/questions/3394835/args-and-kwargs) (*args and **kwargs) – Jamie Czuy Mar 10 '11 at 14:33
  • 1
    Try the Python tutorial instead. [Keyword arguments](https://docs.python.org/2/tutorial/controlflow.html#keyword-arguments). – Ignacio Vazquez-Abrams Mar 10 '11 at 05:39

3 Answers3

9

Based on Keyword arguments' documentation pointed out by @Ignacio Vazquez-Abrams

**kwargs allows you to handle named arguments that you have not defined in advance.

In a function call, keyword arguments must follow positional arguments.

All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important.

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
0

Try this awesome explanation from digital ocean.

In summary, **kwargs is dict that holds parameters and can be used by first passing it through a view func e.g

def fun(req, **kwargs)

and then get values inside the function like this

kwargs.get('key_name').

0

Check this article

def print_kwargs(**kwargs):
    for key in kwargs:
        print("The key {} holds {} value".format(key, kwargs[key]))


print_kwargs(a=1, b=2, c="Some Text")

Output:

The key a holds 1 value
The key b holds 2 value
The key c holds Some Text value
S.B
  • 13,077
  • 10
  • 22
  • 49
Milad
  • 1
  • 3