I find that a lot of people who study Python find it very difficult to understand these two magic variables, *args and **kwargs. How do these two variables work and where do they work?

* and * *

You don’t have to write *args and **kwargs. The only thing that really matters is the *(asterisk) in front of the variable. You can also write *params and **kv_params. In other words, *args and **kwargs are just colloquial, but not required.

* Arguments passed in will be stored as tuples, which is a tuple.

** used before an argument means that the (multiple) arguments passed in will be stored as a dictionary, which is a dictionary.

Below, we will introduce how they are used in the form of code!

Talk is cheap,Show you the code

The use of the * args

*args and **kwargs are mainly used in function definitions. *args is used to send a variable number of arguments to a function with a non-key value pair.

def test_args(normal_arg, *args) :
    print("Normal parameters :", normal_arg)
    print("*args:", args, "Type.".type(args))
    for arg in args:
        print("Parameter passed by *args :", arg)


test_args('python'.'java'.'c/c++'.'go')
Copy the code

The above code execution results are as follows:

*args: ('java'.'c/c++'.'go') Type: <class 'tuple'> by *argsParameter passed:C/C ++ pass *args: goCopy the code

As you can see, it looks like test_args only takes two arguments, but we actually pass four arguments to test_args. The magic is that *args, which is actually a tuple of arguments, is passed to test_args. As you can see, The same is true of the program output above.

The use of the * * kwargs

**kwargs allows you to pass key-value pairs of varying lengths as arguments to a function. If you want to handle named arguments in a function, you use **kwargs. Here’s an example:

def test_kwargs(**kwargs) :
    print("**kwargs:", kwargs, "Type.".type(kwargs))
    for key, value in kwargs.items():
        print("{0} = = {1}".format(key, value))


test_kwargs(name="tom", age="3")
Copy the code

The above code execution results are as follows:

**kwargs: {'name': 'tom'.'age': '3'} type: <class 'dict'>
name= =tom
age= = 3Copy the code

**kwargs assembles multiple arguments into a dictionary passed to the test_kwargs function. At this point, you can see how to handle a key-value pair argument in a function.

Use *args and **kwargs to call functions

So now we’ll see how to call a function using *args and **kwargs. Suppose you have a function that looks like this:

def test_args_kwargs(arg1, arg2, arg3) :
    print("arg1:", arg1)
    print("arg2:", arg2)
    print("arg3:", arg3)
Copy the code

You can pass arguments to this function using *args or **kwargs:

# use *args
args = ("python"."java"."go")
test_args_kwargs(*args)

# use **kwargs
kwargs = {"arg2": "java"."arg3": "go"."arg1": "python"}
test_args_kwargs(**kwargs)
Copy the code

The two calls will give the same output, but * and **kwargs are dereferences of tuples and dictionaries.

conclusion

As long as a function is defined with the keywords *args and **kwargs as arguments, you can pass an indefinite number of arguments of arbitrary type to the function.

Note: so if you want to use all three arguments in the function, in this order: your_func(arg, *args, **kwargs) must not put **kwargs before *args, otherwise an error will be generated.

Finally, I would like to thank my girlfriend for her tolerance, understanding and support in work and life.