Introduction to the Use of *args and **kwargs in django

  • 2021-09-24 23:06:18
  • OfStack

This is the Python function variable parameters args and kwargs

* args represents any number of unnamed parameters, which is one tuple

**kwargs represents a keyword parameter, which is an dict

The test code is as follows:


def foo(*args,**kwargs): print 'args=',args print 'kwargs=',kwargs print '**********************' if __name__=='__main__': foo(1,2,3) foo(a=1,b=2,c=3) foo(1,2,3,a=1,b=2,c=3) foo(1,'b','c',a=1,b='b',c='c')

The implementation results are as follows:


args= (1, 2, 3) kwargs= {} **********************
args= () kwargs= {'a': 1, 'c': 3, 'b': 2} **********************
args= (1, 2, 3) kwargs= {'a': 1, 'c': 3, 'b': 2} **********************
args= (1, 'b', 'c') kwargs= {'a': 1, 'c': 'c', 'b': 'b'} **********************

Add: **kwargs and *args in Python are understood as follows

Two parameters, **kwargs and *args, are often seen in Python, such as the parameters of groupby below.

What exactly does it mean?

How to use it?


DataFrame.groupby(by=None, axis=0, level=None, as_index= True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)

**kwargs and * args mean

* args and **kwargs1 are commonly used in function definition. The meaning of 2 is to allow the defined function to accept any number of parameters. That is to say, before the function is called, we don't know or limit the number of parameters that the function can accept in the future. In this case, we can use *args and **kwargs.

* Use of args

* args is used to indicate that a function accepts a variable-length list of non-keyword arguments as input to the function. We can take the following example one step further to understand * args.


def test_args(normal_arg, *args):
 print("first normal arg:" + normal_arg)
 for arg in args:
  print("another arg through *args :" + arg)
test_args("normal", "python", "java", "C#")

The execution result of the above code is as follows:


first normal arg: normal
another arg through *args : python
another arg through *args : java
another arg through *args :C#

**Use of kwargs

**kwargs indicates that the function accepts a variable-length dictionary of key parameters as input to the function. We should use **kwargs when we want a function to take arguments with keywords as input. We can take the following example one step further to understand **kwargs.


def test_kwargs(**kwargs):
 if kwargs is not None:
  for key, value in kwargs.iteritems():
   print("{} = {}".format(key,value))
  # Or you can visit kwargs like a dict() object
  # for key in kwargs:
  # print("{} = {}".format(key, kwargs[key]))
test_kwargs(name="python", value="5")

The execution results of the above code are as follows:


name = python
value = 5

The above examples are only basic usage examples of *args and **kwargs. Here is another example of using * args and **kwargs to define a function that can accept list input and dictionary input.

Use *args and **kwargs to call functions

For example, we have the following functions that accept common input parameters:


def normal_func(arg1, arg2, arg3):
 print("arg1: " + arg1)
 print("arg2: " + arg2)
 print("arg3: " + arg3)
normal_func("python", 1, 3)

The code to call this function using *args and **kwargs is as follows:


#  Use *args
args_list = ("python", 1, 3)
normal_func(*args_list)
#  Use **kwargs
kwargs_dict = {"arg3": 3, "arg1": "python", "arg2": 1}
normal_func(**kwargs_dict)

The output of the above three codes is:


arg1: python
arg2: 1
arg3: 3

Summary

* args and **kwargs both refer to the problem of the number of internal parameters when defining a function. The specific number is not specified, and the number is determined on the spot according to the specific situation when using it.

* args for non-keyword parameters, **kwargs for keyword parameters.

Not only is it free when defining the function, but it can also be used as an argument when the function is actually called.


Related articles: