Python Language *args and **kwargs

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Remarks

There 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 or more than one kwargs parameters (however they are not required)

     def func(*args1, *args2):
     #   File "<stdin>", line 1
     #     def test(*args1, *args2):
     #                      ^
     # SyntaxError: invalid syntax
    

     def test(**kwargs1, **kwargs2):
     #   File "<stdin>", line 1
     #     def test(**kwargs1, **kwargs2):
     #                       ^
     # SyntaxError: invalid syntax
    
  3. If any positional argument 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):
     #   File "<stdin>", line 1
     #     def test(**kwargs, *args):
     #                      ^
     # SyntaxError: invalid syntax
    


Got any Python Language Question?