Variable Keyword Arguments (kwargs)

🏷️ Functions / Args and Kwargs


🌱 Context Introduction

When building scripts or tools, you often need to create functions that can accept a flexible number of named arguments. This is where kwargs (keyword arguments) come into play. The term kwargs stands for "keyword arguments," and it allows you to pass a variable number of key-value pairs to a function. This is especially useful when you don't know in advance how many named parameters will be provided, or when you want to build functions that can handle optional configuration settings.


⚙️ What Are Variable Keyword Arguments (kwargs)?

  • kwargs is a special syntax in Python that collects any extra keyword arguments passed to a function into a dictionary.
  • The double asterisk () before the parameter name (usually kwargs) tells Python to capture all named arguments that were not explicitly defined in the function signature.
  • Inside the function, **kwargs behaves like a regular Python dictionary where:
  • The keys are the argument names (as strings).
  • The values are the corresponding argument values.
  • You can name the parameter anything you like, but kwargs is the widely accepted convention.

🛠️ How to Define and Use kwargs

Basic Syntax:

  • Define a function with kwargs as the last parameter: def my_function(kwargs):
  • Inside the function, access the dictionary like any other: kwargs['key'] or kwargs.get('key')
  • Call the function by passing any number of keyword arguments: my_function(name='Alice', role='engineer', years=5)

Simple Example:

  • Function definition: def print_settings(kwargs):**
  • Inside the function: for key, value in kwargs.items(): print(f'{key}: {value}')
  • Function call: print_settings(host='localhost', port=8080, debug=True)
  • Expected output:
  • host: localhost
  • port: 8080
  • debug: True

📊 Comparison: Regular Parameters vs kwargs

Feature Regular Parameters Variable Keyword Arguments (kwargs)
Number of arguments Fixed, defined in function signature Variable, any number of named arguments
Data type received Individual variables Dictionary
Flexibility Must match exactly Accepts any key-value pairs
Use case When you know exactly what you need When you need optional or dynamic parameters
Order requirement Positional order matters No order requirement (named)

🕵️ Common Use Cases for kwargs

  • Configuration functions: Passing multiple settings or options without defining each one explicitly.
  • Wrapper or decorator functions: Forwarding arguments to another function without knowing all parameters in advance.
  • Database query builders: Passing column names and values dynamically.
  • API request handlers: Accepting optional parameters for filtering, sorting, or pagination.
  • Logging utilities: Allowing custom metadata to be attached to log messages.

🧩 Combining kwargs with Regular Parameters

You can mix regular parameters with kwargs, but kwargs must always come last in the function signature.

Example structure:

  • def create_user(username, age, kwargs):**
  • Regular parameters: username and age are required.
  • kwargs captures any additional named arguments like email='[email protected]' or role='admin'

Calling the function:

  • create_user('john_doe', 30, email='[email protected]', role='engineer')
  • Inside the function, username is 'john_doe', age is 30, and kwargs is {'email': '[email protected]', 'role': 'engineer'}

🎯 Practical Tips for Using kwargs

  • Always use kwargs as the parameter name for consistency and readability.
  • Access dictionary values safely using kwargs.get('key') instead of kwargs['key'] to avoid KeyError if a key is missing.
  • Use kwargs when you want to make your functions extensible without breaking existing code.
  • Document the expected keys in your function's docstring so other engineers know what to pass.
  • Avoid overusing kwargs for functions that have a small, fixed set of parameters — explicit parameters are clearer.

🚦 Common Mistakes to Avoid

  • Placing **kwargs before regular parameters in the function definition.
  • Forgetting that **kwargs is a dictionary, not a list or tuple.
  • Assuming a key exists without checking — always use .get() or test with in.
  • Using kwargs when the function truly needs a fixed set of named parameters — this reduces code clarity.
  • Naming the parameter something confusing instead of the standard kwargs.

✅ Summary

  • kwargs allows a function to accept any number of keyword arguments as a dictionary.
  • It provides flexibility for building functions that can handle dynamic or optional named parameters.
  • Combine kwargs with regular parameters for maximum control and readability.
  • Use kwargs wisely — it's powerful for extensibility but can obscure the function's expected inputs if overused.

With kwargs in your toolkit, you can write more adaptable and reusable functions that gracefully handle a wide range of inputs.


Variable keyword arguments (**kwargs) let a function accept any number of named arguments as a dictionary.

📘 Example 1: Basic **kwargs — capturing named arguments

This shows how **kwargs collects all extra named arguments into a dictionary.

def show_details(**kwargs):
    print(kwargs)

show_details(name="Alice", role="engineer")

📤 Output: {'name': 'Alice', 'role': 'engineer'}


📘 Example 2: Mixing regular parameters with **kwargs

This demonstrates combining a fixed parameter with variable keyword arguments.

def greet(greeting, **kwargs):
    print(f"{greeting}, {kwargs['name']}!")
    print(f"Your details: {kwargs}")

greet("Hello", name="Bob", department="mechanical")

📤 Output: Hello, Bob!
📤 Output: Your details: {'name': 'Bob', 'department': 'mechanical'}


📘 Example 3: Iterating over **kwargs items

This shows how to loop through all keyword arguments using .items().

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

print_config(host="localhost", port=8080, debug=True)

📤 Output: host = localhost
📤 Output: port = 8080
📤 Output: debug = True


📘 Example 4: Using **kwargs to pass arguments to another function

This demonstrates forwarding keyword arguments from one function to another.

def connect(host, port, **kwargs):
    print(f"Connecting to {host}:{port}")
    if kwargs.get("timeout"):
        print(f"Timeout set to {kwargs['timeout']} seconds")

def setup_connection(**kwargs):
    print("Setting up connection...")
    connect(**kwargs)

setup_connection(host="10.0.0.1", port=22, timeout=30)

📤 Output: Setting up connection...
📤 Output: Connecting to 10.0.0.1:22
📤 Output: Timeout set to 30 seconds


📘 Example 5: Practical use — building a URL query string

This shows a real-world pattern where **kwargs builds dynamic parameters.

def build_url(base, **params):
    query_parts = []
    for key, value in params.items():
        query_parts.append(f"{key}={value}")
    query_string = "&".join(query_parts)
    return f"{base}?{query_string}"

url = build_url("https://api.example.com/data", sensor="temp", unit="celsius", limit=10)
print(url)

📤 Output: https://api.example.com/data?sensor=temp&unit=celsius&limit=10


📊 Comparison: args vs *kwargs

Feature *args **kwargs
What it collects Positional arguments Keyword (named) arguments
Data type Tuple Dictionary
Access items args[0], args[1], ... kwargs['key'] or kwargs.get('key')
Typical use Variable number of values Variable number of named options

🌱 Context Introduction

When building scripts or tools, you often need to create functions that can accept a flexible number of named arguments. This is where kwargs (keyword arguments) come into play. The term kwargs stands for "keyword arguments," and it allows you to pass a variable number of key-value pairs to a function. This is especially useful when you don't know in advance how many named parameters will be provided, or when you want to build functions that can handle optional configuration settings.


⚙️ What Are Variable Keyword Arguments (kwargs)?

  • kwargs is a special syntax in Python that collects any extra keyword arguments passed to a function into a dictionary.
  • The double asterisk () before the parameter name (usually kwargs) tells Python to capture all named arguments that were not explicitly defined in the function signature.
  • Inside the function, **kwargs behaves like a regular Python dictionary where:
  • The keys are the argument names (as strings).
  • The values are the corresponding argument values.
  • You can name the parameter anything you like, but kwargs is the widely accepted convention.

🛠️ How to Define and Use kwargs

Basic Syntax:

  • Define a function with kwargs as the last parameter: def my_function(kwargs):
  • Inside the function, access the dictionary like any other: kwargs['key'] or kwargs.get('key')
  • Call the function by passing any number of keyword arguments: my_function(name='Alice', role='engineer', years=5)

Simple Example:

  • Function definition: def print_settings(kwargs):**
  • Inside the function: for key, value in kwargs.items(): print(f'{key}: {value}')
  • Function call: print_settings(host='localhost', port=8080, debug=True)
  • Expected output:
  • host: localhost
  • port: 8080
  • debug: True

📊 Comparison: Regular Parameters vs kwargs

Feature Regular Parameters Variable Keyword Arguments (kwargs)
Number of arguments Fixed, defined in function signature Variable, any number of named arguments
Data type received Individual variables Dictionary
Flexibility Must match exactly Accepts any key-value pairs
Use case When you know exactly what you need When you need optional or dynamic parameters
Order requirement Positional order matters No order requirement (named)

🕵️ Common Use Cases for kwargs

  • Configuration functions: Passing multiple settings or options without defining each one explicitly.
  • Wrapper or decorator functions: Forwarding arguments to another function without knowing all parameters in advance.
  • Database query builders: Passing column names and values dynamically.
  • API request handlers: Accepting optional parameters for filtering, sorting, or pagination.
  • Logging utilities: Allowing custom metadata to be attached to log messages.

🧩 Combining kwargs with Regular Parameters

You can mix regular parameters with kwargs, but kwargs must always come last in the function signature.

Example structure:

  • def create_user(username, age, kwargs):**
  • Regular parameters: username and age are required.
  • kwargs captures any additional named arguments like email='[email protected]' or role='admin'

Calling the function:

  • create_user('john_doe', 30, email='[email protected]', role='engineer')
  • Inside the function, username is 'john_doe', age is 30, and kwargs is {'email': '[email protected]', 'role': 'engineer'}

🎯 Practical Tips for Using kwargs

  • Always use kwargs as the parameter name for consistency and readability.
  • Access dictionary values safely using kwargs.get('key') instead of kwargs['key'] to avoid KeyError if a key is missing.
  • Use kwargs when you want to make your functions extensible without breaking existing code.
  • Document the expected keys in your function's docstring so other engineers know what to pass.
  • Avoid overusing kwargs for functions that have a small, fixed set of parameters — explicit parameters are clearer.

🚦 Common Mistakes to Avoid

  • Placing **kwargs before regular parameters in the function definition.
  • Forgetting that **kwargs is a dictionary, not a list or tuple.
  • Assuming a key exists without checking — always use .get() or test with in.
  • Using kwargs when the function truly needs a fixed set of named parameters — this reduces code clarity.
  • Naming the parameter something confusing instead of the standard kwargs.

✅ Summary

  • kwargs allows a function to accept any number of keyword arguments as a dictionary.
  • It provides flexibility for building functions that can handle dynamic or optional named parameters.
  • Combine kwargs with regular parameters for maximum control and readability.
  • Use kwargs wisely — it's powerful for extensibility but can obscure the function's expected inputs if overused.

With kwargs in your toolkit, you can write more adaptable and reusable functions that gracefully handle a wide range of inputs.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

Variable keyword arguments (**kwargs) let a function accept any number of named arguments as a dictionary.

📘 Example 1: Basic **kwargs — capturing named arguments

This shows how **kwargs collects all extra named arguments into a dictionary.

def show_details(**kwargs):
    print(kwargs)

show_details(name="Alice", role="engineer")

📤 Output: {'name': 'Alice', 'role': 'engineer'}


📘 Example 2: Mixing regular parameters with **kwargs

This demonstrates combining a fixed parameter with variable keyword arguments.

def greet(greeting, **kwargs):
    print(f"{greeting}, {kwargs['name']}!")
    print(f"Your details: {kwargs}")

greet("Hello", name="Bob", department="mechanical")

📤 Output: Hello, Bob!
📤 Output: Your details: {'name': 'Bob', 'department': 'mechanical'}


📘 Example 3: Iterating over **kwargs items

This shows how to loop through all keyword arguments using .items().

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

print_config(host="localhost", port=8080, debug=True)

📤 Output: host = localhost
📤 Output: port = 8080
📤 Output: debug = True


📘 Example 4: Using **kwargs to pass arguments to another function

This demonstrates forwarding keyword arguments from one function to another.

def connect(host, port, **kwargs):
    print(f"Connecting to {host}:{port}")
    if kwargs.get("timeout"):
        print(f"Timeout set to {kwargs['timeout']} seconds")

def setup_connection(**kwargs):
    print("Setting up connection...")
    connect(**kwargs)

setup_connection(host="10.0.0.1", port=22, timeout=30)

📤 Output: Setting up connection...
📤 Output: Connecting to 10.0.0.1:22
📤 Output: Timeout set to 30 seconds


📘 Example 5: Practical use — building a URL query string

This shows a real-world pattern where **kwargs builds dynamic parameters.

def build_url(base, **params):
    query_parts = []
    for key, value in params.items():
        query_parts.append(f"{key}={value}")
    query_string = "&".join(query_parts)
    return f"{base}?{query_string}"

url = build_url("https://api.example.com/data", sensor="temp", unit="celsius", limit=10)
print(url)

📤 Output: https://api.example.com/data?sensor=temp&unit=celsius&limit=10


📊 Comparison: args vs *kwargs

Feature *args **kwargs
What it collects Positional arguments Keyword (named) arguments
Data type Tuple Dictionary
Access items args[0], args[1], ... kwargs['key'] or kwargs.get('key')
Typical use Variable number of values Variable number of named options