Sobes.tech
Junior

What is kwargs in Python?

sobes.tech AI

Answer from AI

**kwargs in Python is syntax for passing an arbitrary number of named arguments to a function. The letters kw stand for keyword, and args for arguments.

When a function is defined with the parameter **kwargs, it collects all the passed named arguments that do not match explicit function parameters into a dictionary. The keys of this dictionary correspond to the argument names, and the values are the passed values.

Main purposes of **kwargs:

  • Function flexibility: Allows creating functions that can accept various sets of named arguments without explicitly defining each one.
  • Passing arguments further: Convenient for passing arguments from one function to another, especially when using decorator patterns or working with APIs of other libraries where the set of parameters may be unknown in advance.

Example of usage:

def my_function(arg1, **kwargs):
    print(f"arg1: {arg1}")
    if kwargs:
        print("Other named arguments:")
        for key, value in kwargs.items():
            print(f"  {key}: {value}")

my_function("Mandatory argument", param1=10, param2="hello")
# Output:
# arg1: Mandatory argument
# Other named arguments:
#   param1: 10
#   param2: hello

my_function("Only mandatory")
# Output:
# arg1: Only mandatory

Important points:

  • The name of the parameter **kwargs is a convention, but any other valid name can be used after **.
  • Parameters *args (for positional arguments) and **kwargs can be used together in function definitions. The order should be: regular parameters, *args, **kwargs.
  • **kwargs must be the last parameter collecting arguments.

Comparison with *args:

Feature *args **kwargs
Type of collected data Tuple (tuple) Dictionary (dict)
Passed data Unnamed (positional) arguments Named (keyword) arguments
Call syntax func(1, 2, 3) func(name="Alice", age=30)
Definition syntax def func(*args): def func(**kwargs):

Using ** in function call (unpacking a dictionary):

You can use the ** operator when calling a function to unpack a dictionary and pass its elements as named arguments.

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

params = {"name": "Bob", "greeting": "Hi"}
greet(**params) # Equivalent to greet(name="Bob", greeting="Hi")