0
0
PythonConceptBeginner · 3 min read

What is kwargs in Python: Explanation and Examples

kwargs in Python stands for "keyword arguments" and allows a function to accept any number of named arguments as a dictionary. It is written as **kwargs in the function definition and helps handle flexible inputs.
⚙️

How It Works

Imagine you have a gift box that can hold any number of small gifts, each labeled with a name. In Python, **kwargs works like that gift box for functions. When you define a function with **kwargs, it collects all extra named inputs into a dictionary inside the function.

This means you don’t have to know in advance how many named arguments the function will get. The function can then use these arguments by their names, just like picking gifts by their labels.

💻

Example

This example shows a function that prints all the named arguments it receives using **kwargs.

python
def greet(**kwargs):
    for name, message in kwargs.items():
        print(f"{name} says: {message}")

greet(Alice="Hello!", Bob="Good morning!", Carol="Hi there!")
Output
Alice says: Hello! Bob says: Good morning! Carol says: Hi there!
🎯

When to Use

Use **kwargs when you want your function to accept extra named arguments that you might not know beforehand. This is helpful for writing flexible functions that can handle different options or settings.

For example, when creating a function that configures a user profile, you might want to accept various optional details like age, city, or hobby without listing them all explicitly.

Key Points

  • **kwargs collects extra named arguments as a dictionary.
  • It allows functions to be flexible with input parameters.
  • You access the arguments inside the function by their names (keys).
  • It is often used with *args, which collects extra unnamed arguments.

Key Takeaways

**kwargs lets functions accept any number of named arguments as a dictionary.
It helps write flexible functions that can handle extra options without changing the code.
Inside the function, you access kwargs items by their keys (argument names).
Use **kwargs when you want to allow optional or unknown named inputs.
Often combined with *args to handle both named and unnamed extra arguments.