Examples are given to illustrate the usage of *args and **kwargs in python

  • 2020-04-02 13:03:46
  • OfStack

Here's an 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)

The output results are as follows:

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

As you can see from the above examples, these two are mutable parameters in python. *args represents any number of unnamed arguments, which is a tuple; **kwargs represents a keyword parameter, which is a dict. And when *args and **kwargs are used together, the *args parameter column must be called before **kwargs, like foo(a=1, b='2', c=3, a', 1, None,), prompting a SyntaxError "SyntaxError: non-keyword arg after keyword arg". As shown:


Related articles: