Menu
Coddy logo textTech

The **kwarg

Part of the Object Oriented Programming section of Coddy's Python journey — lesson 43 of 64.

**kwargs is short for "keyword arguments". It allows a function to accept any number of named arguments (like key=value pairs) without having to define them all in advance.

How it works:

  • *args → collects extra positional arguments into a tuple
  • **kwargs → collects extra keyword arguments into a dictionary

Simple Example

Let's start with the simplest possible example:

def greet(**kwargs):
    print(kwargs)

greet(name="Alice", age=25, country="Australia")

Output:

{'name': 'Alice', 'age': 25, 'country': 'Australia'}

As you can see, **kwargs automatically collects all the keyword arguments into a dictionary.

Using the Dictionary

Since kwargs is already a dictionary, you can loop through it directly:

def print_info(**kwargs):
    print("Information received:")
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Bob", age=30, job="Teacher")

Output:

Information received:
name: Bob
age: 30
job: Teacher

Mixing Regular Parameters with **kwargs

You can combine regular parameters with **kwargs:

def create_profile(name, **details):
    print(f"Creating profile for: {name}")
    print("Additional details:")
    for key, value in details.items():
        print(f"  {key}: {value}")

create_profile("Sarah", age=28, city="London", hobby="Reading")

Output:

Creating profile for: Sarah
Additional details:
  age: 28
  city: London
  hobby: Reading

Empty **kwargs

If no keyword arguments are passed, kwargs will be an empty dictionary:

def show_data(**kwargs):
    if kwargs:
        print("Data:", kwargs)
    else:
        print("No data provided")

show_data()  # No arguments
show_data(item="apple")  # With arguments

Output:

No data provided
Data: {'item': 'apple'}

Real-World Example: Class with **kwargs

Here's how you might use **kwargs in a class:

class Person:
    def __init__(self, name, **kwargs):
        self.name = name
        self.details = kwargs
    
    def show_info(self):
        print(f"Name: {self.name}")
        for key, value in self.details.items():
            print(f"{key}: {value}")

person = Person("Alice", age=25, city="New York", job="Engineer")
person.show_info()

Output:

Name: Alice
age: 25
city: New York
job: Engineer

Unpacking Dictionaries

You can also unpack dictionaries when calling functions:

def display_settings(**kwargs):
    for setting, value in kwargs.items():
        print(f"{setting} = {value}")

settings = {"debug": True, "verbose": False, "timeout": 30}
display_settings(**settings)  # Unpacks the dictionary

Output:

debug = True
verbose = False
timeout = 30

Key Points:

  • **kwargs collects keyword arguments into a dictionary — no conversion needed, it's already one
  • The name kwargs is conventional - you could use any name after **
  • Use it when you want flexible function signatures
  • Great for handling optional parameters or configuration settings
challenge icon

Challenge

Easy

In this challenge, you'll implement a person creation system with comprehensive test coverage.

You need to edit only the person_creator.py file, following the TODO comments that guide your implementation. The file contains a class structure for creating and managing person objects with various properties.

Cheat sheet

The **kwargs parameter allows a method to accept any number of keyword arguments, collecting them into a dictionary:

class Person:
    def __init__(self, name, **kwargs):
        self.name = name
        self.details = kwargs
    
    def show_info(self):
        print(f"Name: {self.name}")
        for key, value in self.details.items():
            print(f"{key}: {value}")

person = Person("Alice", age=25, city="New York", job="Engineer")

Combine regular parameters, *args, and **kwargs:

class Logger:
    def log(self, level, *messages, **options):
        timestamp = options.get('timestamp', False)
        color = options.get('color', 'default')
        
        if timestamp:
            print("[2024-01-01 12:00:00]", end=" ")
        print(f"[{level}]", end=" ")
        for message in messages:
            print(message, end=" ")

logger = Logger()
logger.log("INFO", "User", "logged", "in", timestamp=True, color="green")

Unpack dictionaries when calling methods using **:

settings = {"debug": True, "verbose": False, "log_level": "INFO"}
config = Config(**settings)  # Unpacks the dictionary

Access **kwargs values using dictionary methods:

def get_setting(self, key, default=None):
    return self.settings.get(key, default)

# Iterate through all kwargs
for key, value in self.settings.items():
    print(f"{key} = {value}")

Try it yourself

from person_creator import create_person

# Comprehensive test case handler
test_case = input()

if test_case == "basic_test":
    create_person(name="John", age=25, occupation="Engineer")
    # Output:
    # Person created with properties:
    # name: John
    # age: 25
    # occupation: Engineer

elif test_case == "empty_test":
    create_person()
    # Output:
    # Person created with properties:
    # (no additional output since there are no properties)

elif test_case == "many_properties":
    create_person(name="Alice", age=30, occupation="Doctor", city="New York", 
                 country="USA", hobby="Reading", email="alice@example.com")
    # Output:
    # Person created with properties:
    # name: Alice
    # age: 30
    # occupation: Doctor
    # city: New York
    # country: USA
    # hobby: Reading
    # email: alice@example.com

elif test_case == "special_characters":
    create_person(name="Bob", email="bob@example.com", phone="123-456-7890")
    # Output:
    # Person created with properties:
    # name: Bob
    # email: bob@example.com
    # phone: 123-456-7890

elif test_case == "numeric_keys":
    create_person(name="Charlie", age=35, height=175, weight=70)
    # Output:
    # Person created with properties:
    # name: Charlie
    # age: 35
    # height: 175
    # weight: 70

elif test_case == "boolean_values":
    create_person(name="David", is_student=True, is_employed=False)
    # Output:
    # Person created with properties:
    # name: David
    # is_student: True
    # is_employed: False

elif test_case == "nested_structures":
    create_person(name="Eve", hobbies=["Reading", "Swimming", "Coding"], 
                 address={"city": "Boston", "state": "MA", "zip": "02108"})
    # Output:
    # Person created with properties:
    # name: Eve
    # hobbies: ['Reading', 'Swimming', 'Coding']
    # address: {'city': 'Boston', 'state': 'MA', 'zip': '02108'}

elif test_case == "unicode_characters":
    create_person(name="José", city="São Paulo", country="Brasil")
    # Output:
    # Person created with properties:
    # name: José
    # city: São Paulo
    # country: Brasil
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming