args and kwargs

suggest change

Remarks

There are a few things to note:

  1. The names args and kwargs are used by convention, they are not a part of the language specification. Thus, these are equivalent:

    def func(*args, **kwargs):
        print(args)
        print(kwargs)
    #
    def func(*a, **b):
        print(a)
        print(b)
    
  2. You may not have more than one *args parameter or more than one **kwargs parameter (though neither is required)

    def func(*args1, *args2):
    # SyntaxError: * argument may appear only once
    #
    def test(**kwargs1, **kwargs2):
    # SyntaxError: arguments cannot follow var-keyword argument
    
  3. If any positional arguments follow *args, they are keyword-only arguments that can only be passed by name. A single star may be used instead of *args to force values to be keyword arguments without providing a variadic parameter list. Keyword-only parameter lists are only available in Python 3.

    def func(a, b, *args, x, y):
        print(a, b, args, x, y)
    
    func(1, 2, 3, 4, x=5, y=6)
    # 1 2 (3, 4) 5 6
    #
    def func(a, b, *, x, y):
        print(a, b, x, y)
    
    func(1, 2, x=5, y=6)
    # 1 2 5 6
    
  4. **kwargs must come last in the parameter list.

    def test(**kwargs, *args):
    # SyntaxError: arguments cannot follow var-keyword argument
    

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents