args and **kwargs in Python

http://book.pythontips.com/en/latest/args_and_kwargs.html

https://stackoverflow.com/questions/3394835/use-of-args-and-kwargs

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)

get_fullname('Leo','Messi')
# 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):
    fullname=''
    for name in args:
        fullname+=' '+name
    print(type(args))
    print(fullname)

get_fullname('Lionel','Andrés','Messi')
# <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:

tup=('Lionel','Andrés','Messi')
def get_fullname(*args):
    fullname=''
    for name in args:
        fullname+=' '+name
    print(type(args))
    print(fullname)

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 = {
          'host':'10.0.1.200',
          'port':6033,
          'user':'leo',
          'password':'leo',
          'db':'test',
          'charset':'utf8'
          }
try:
    conn=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:
            cursor.execute(sql)
            result = cursor.fetchall()
            return result
        self.conn.commit()

    def _close(self):
        self.conn.close()

    def get_version(self):
        version = self._query("select VARIABLE_NAME,VARIABLE_VALUE from information_schema.SESSION_VARIABLES where "
                              "VARIABLE_NAME in ('VERSION_COMMENT','VERSION','VERSION_COMPILE_MACHINE',"
                              "'VERSION_COMPILE_OS');")
        return version
 

if __name__ == '__main__':
    conn_dict = { 'host': '10.1.1.11' , '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='10.1.1.11',port=3306,user= 'leo',password='leo')
    version = testServer.get_version()
    print(version)

 

Keywords: Python SQL github

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