Understand * args and ** kwargs of s variable parameters in Python

Source: Internet
Author: User
Python supports variable parameters. The simplest method is to use default parameters. This document describes the use of * args and ** kwargs.

Variable parameters with default parameters

Python supports variable parameters. The simplest method is to use default parameters. for example:

def test_defargs(one, two = 2):   print 'Required argument: ', one   print 'Optional argument: ', twotest_defargs(1)# result:# Required argument: 1# Optional argument: 2test_defargs(1, 3)# result:# Required argument: 1# Optional argument: 3

When defining a function, use * args and ** kwargs

Of course, this article mainly describes a method to achieve Variable Argument: use the * args and ** kwargs syntax. Here, * args is the variable positional arguments list, and ** kwargs is the variable keyword arguments list. In addition, * args must be located before ** kwargs, because positional arguments must be located before keyword arguments.

First, we will introduce the basic usage of the two.

The following example uses * args and contains a required parameter:

def test_args(first, *args):   print 'Required argument: ', first   for v in args:      print 'Optional argument: ', vtest_args(1, 2, 3, 4)# result:# Required argument: 1# Optional argument:  2# Optional argument:  3# Optional argument:  4

The following example uses * kwargs and contains a required parameter and * args list:

def test_kwargs(first, *args, **kwargs):   print 'Required argument: ', first   for v in args:      print 'Optional argument (*args): ', v   for k, v in kwargs.items():      print 'Optional argument %s (*kwargs): %s' % (k, v)test_kwargs(1, 2, 3, 4, k1=5, k2=6)# results:# Required argument:  1# Optional argument (*args):  2# Optional argument (*args):  3# Optional argument (*args):  4# Optional argument k2 (*kwargs): 6# Optional argument k1 (*kwargs): 5

When calling a function, use * args and ** kwargs

* Args and ** kwargs syntaxes can be used not only in function definitions, but also in function calls. The difference is that if * args and ** kwargs are used in the function definition position to pack the parameter, it is a process of unpack the parameter when the function is called. The following example is used to deepen understanding:

def test_args(first, second, third, fourth, fifth):    print 'First argument: ', first    print 'Second argument: ', second    print 'Third argument: ', third    print 'Fourth argument: ', fourth    print 'Fifth argument: ', fifth# Use *argsargs = [1, 2, 3, 4, 5]test_args(*args)# results:# First argument:  1# Second argument:  2# Third argument:  3# Fourth argument:  4# Fifth argument:  5# Use **kwargskwargs = {    'first': 1,    'second': 2,    'third': 3,    'fourth': 4,    'fifth': 5}test_args(**kwargs)# results:# First argument:  1# Second argument:  2# Third argument:  3# Fourth argument:  4# Fifth argument:  5

You can use * args and ** kwargs to easily define functions and enhance scalability for future code maintenance.

Example

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

Note:

Note: When defining or calling such a function, follow the following rules:
Variable parameters must follow the immutable parameters
* Args is a variable positional arguments list, and ** kwargs is a variable keyword arguments list. In addition, * args must be located before ** kwargs, because positional arguments must be located before keyword arguments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.