Skip to content

Module 9 · Functions — topic 10 of 19

**kwargs

Accepting arbitrary keyword arguments with **kwargs, working with the resulting dictionary, the full parameter order, and forwarding *args and **kwargs together.

Beginner 8 min read·Lesson 135 of 306 in Python Programming

Learning objectives

  • Write functions that accept arbitrary keyword arguments
  • Order all kinds of parameters correctly
  • Forward *args and **kwargs to another function

Definition

A parameter written as **kwargs collects all keyword arguments that don't match another parameter into a dictionary mapping names to values.

Introduction

Sometimes a function should accept named options it doesn't know in advance — HTML attributes, database filters, settings to pass on. **kwargs gathers them into a dictionary.

Why it matters

**kwargs powers flexible APIs and is how wrappers pass every argument through: def wrapper(*args, **kwargs): return func(*args, **kwargs).

Detailed explanation

kwargs is an ordinary dict: iterate it, use .get() for optional values, or check 'key' in kwargs.

Since Python 3.7, the dictionary keeps the order in which the keywords were passed.

The full order of parameter kinds is: positional-only, /, regular, *args (or a bare *), keyword-only, **kwargs. For example def f(a, b=2, *args, c, d=4, **kwargs).

In a call, **mapping unpacks a dictionary into keyword arguments; together with *args this forwards everything.

Avoid **kwargs when you know the allowed options — explicit parameters are easier to read, document and check for typos.

Syntax

Python
def html_tag(name, content, **attributes):
attrs = "".join(f' {k}="{v}"' for k, v in attributes.items())
return f"<{name}{attrs}>{content}</{name}>"
def wrapper(*args, **kwargs):
return target(*args, **kwargs)
  • kwargs is a dict.
  • **kwargs must be the last parameter.
  • f(**d) unpacks a dict in a call.

Code examples

Collecting named options

Python
def html_tag(name, content, **attributes):
attrs = "".join(f' {k}="{v}"' for k, v in attributes.items())
return f"<{name}{attrs}>{content}</{name}>"
print(html_tag("a", "Docs", href="/docs", target="_blank"))
print(html_tag("p", "Plain text"))
Output
<a href="/docs" target="_blank">Docs</a>
<p>Plain text</p>

All parameter kinds together

Python
def show(a, b=2, *args, c, d=4, **kwargs):
print(a, b, args, c, d, kwargs)
show(1, c=3)
show(1, 5, 6, 7, c=8, e=9, f=10)
Output
1 2 () 3 4 {}
1 5 (6, 7) 8 4 {'e': 9, 'f': 10}

More examples

Filtering records with keyword criteria

Python
students = [
{"name": "Asha", "branch": "CSE", "year": 2},
{"name": "Ravi", "branch": "ECE", "year": 2},
{"name": "Meera", "branch": "CSE", "year": 3},
]
def find(records, **criteria):
return [r["name"] for r in records if all(r.get(k) == v for k, v in criteria.items())]
print(find(students, branch="CSE"))
print(find(students, year=2))
print(find(students, branch="CSE", year=3))
filters = {"branch": "ECE"}
print(find(students, **filters))
Output
['Asha', 'Meera']
['Asha', 'Ravi']
['Meera']
['Ravi']

Step-by-step explanation

  • criteria is a dict of every keyword passed, e.g. {'branch': 'CSE', 'year': 3}.
  • all(...) keeps a record only if it matches every criterion.
  • With no criteria, all() of an empty sequence is True, so every name would be returned.
  • **filters unpacks a dictionary built elsewhere into the same keywords.

Expected output

Running “Filtering records with keyword criteria” prints exactly:

TextOutput
['Asha', 'Meera']
['Asha', 'Ravi']
['Meera']
['Ravi']

Practical applications

  • ORMs filter with keywords: User.objects.filter(city="Pune", active=True).
  • Plotting libraries accept many styling options through **kwargs.

Best practices

  • Prefer explicit parameters when the options are known.
  • Use *args, **kwargs to forward arguments in wrappers.
  • Validate unexpected keys if correctness matters.

Common mistakes

Typos disappear into kwargs

Avoid

def save(data, **kwargs):
if kwargs.get("compress"): ...
save(d, compres=True) # silently ignored

Prefer

def save(data, *, compress=False): ...

With explicit keyword-only parameters, a misspelled name raises TypeError instead of being ignored.

**kwargs not last

Avoid

def f(**kwargs, x): ...

Prefer

def f(x, **kwargs): ...

**kwargs must be the final parameter (SyntaxError otherwise).

Important notes

  • Keyword names in **kwargs must be valid identifiers when passed literally; via ** unpacking a dict, keys must still be strings.

Key takeaways

  • **kwargs collects extra keyword arguments into a dict.
  • Parameter order: regular, *args, keyword-only, **kwargs.
  • f(*args, **kwargs) forwards everything.

Try it yourself

  1. 1
    Write make_profile(name, **details) that returns a formatted multi-line string of all details.
  2. 2
    Write a wrapper that prints the arguments of any function call before calling it.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic