args and **kwargs in Python

Many new Python users will be confused about the source code of github and python standard library as well as various * args and **kwargs in the online examples. Here's an explanation.

First of all:

*Args and * * kwargs (key word args) are just a conventional way of writing, which is equivalent to using... End when we enumerate some transactions, you can also use... Or... Or ~ ~ ~ ~ and so on. The important thing is that * and * * are prefixes. You can also use * inputs or * * inputs.

*args and * * kwargs are often used to introduce function usage in many python related official websites. Their function is to represent multiple parameters. This will be explained later.

In general, * args and * * kwargs are not needed when defining a method or class, such as the following functions:

def get_fullname(first_name,last_name):
    print(first_name+' '+last_name)

# Leo Messi

But what if the number of input parameters is uncertain? Because the input parameters are uncertain, we cannot determine how many input parameters to define. In this case, * args is useful:

def get_fullname(*args):
    for name in args:
        fullname+=' '+name

# <class 'tuple'>
# Lionel Andrés Messi

It can be seen that * args is used to represent multiple input parameters. python stores multiple input parameters into a tuple named args by default. However, note that this tuple is not an input parameter in itself. After the * prefix is added, * args means that each element in the ancestor is treated as an input parameter (location parameter).

Of course, it is also feasible to define a tuple directly and then take it as a parameter. python will parse the tuple into the input parameter of location parameter, for example:

def get_fullname(*args):
    for name in args:
        fullname+=' '+name

get_fullname(*tup)  //Note that * must be added before tup to indicate that input parameters are processed as tuples. Otherwise, the tuple itself will be treated as an input parameter.
# <class 'tuple'>
# Lionel Andrés Messi

As for * * kwargs, its function is very well explained. It is similar to * args. The difference is that * args treats the parameter list as a tuple, while * * kwargs treats the parameter list as a dict. You can either pass in multiple parameters in the format of key=value, or directly pass in a dictionary as in the following example:

from pymysql import Connect
config = {

Here config is a dict, * * config means that the key values of this dict are resolved to multiple input parameters of key=value.

Complete example:

import pymysql

class BasicServer(object):
    def __init__(self , **kwargs):
        self.conn = pymysql.connect(**kwargs)
		# Here * * kwargs is used to represent multiple input parameters, which can only be in the format of key=value, or a dict is passed in directly.
    def _query(self , sql):
        with self.conn.cursor() as cursor:
            result = cursor.fetchall()
            return result

    def _close(self):

    def get_version(self):
        version = self._query("select VARIABLE_NAME,VARIABLE_VALUE from information_schema.SESSION_VARIABLES where "
        return version

if __name__ == '__main__':
    conn_dict = { 'host': '' , 'port': 3306 , 'db': None , 'user': 'leo' ,
                  'password': 'leo' , 'charset': 'utf8' , 'cursorclass': pymysql.cursors.DictCursor }
    testServer = BasicServer(**conn_dict)
    # The above two lines of code can also be replaced by one line of code as follows:
    # testServer = BasicServer(host='',port=3306,user= 'leo',password='leo')
    version = testServer.get_version()


Keywords: Python SQL github

Added by sobbayi on Wed, 23 Oct 2019 05:42:04 +0300