Sub topic 3
**kwargs: accepting any number of keyword arguments
This chapter assumes you can define and call functions, use default parameter values, and work with dictionaries, including looping over one with items(). It also assumes you have seen *args, which collects extra positional arguments. Here the focus is its keyword counterpart, **kwargs.
By the end you will know what **kwargs collects, how to read and validate its contents, how it interacts with named parameters, and which errors it causes or hides.
What **kwargs collects
Normally a function accepts only the keyword names listed in its signature. If a caller passes a name the function does not list, Python raises a TypeError. Adding a parameter prefixed with ** changes this. Every keyword argument that does not match another parameter is collected into a dictionary.
def show(**kwargs):
for key, value in kwargs.items():
print(f"{key}={value}")
show(name="Ada", age=36)
# name=Ada
# age=36The ** is the syntax that matters. The name kwargs is only a convention, short for "keyword arguments". def show(**options) behaves identically, and a more specific name often makes code easier to read. Use kwargs when the function really accepts anything, and a descriptive name such as attrs, options, or style when the keywords have a purpose.
The collected value is a dictionary
Inside the function, kwargs is an ordinary dict. Its keys are the argument names as strings. Its values are whatever the caller passed.
def inspect_kwargs(**kwargs):
print(type(kwargs), kwargs)
inspect_kwargs()
inspect_kwargs(a=1, b=2)
# <class 'dict'> {}
# <class 'dict'> {'a': 1, 'b': 2}Three properties follow from this.
- It is never
None. With no extra keywords,kwargsis an empty dictionary, so you can loop over it or call.get()without a check. - Order is preserved. The dictionary keeps the order in which the caller wrote the keywords. Python guarantees this from version 3.7 onward.
- It is a fresh dictionary on every call. Changing
kwargsinside the function never changes anything in the caller, even when the caller used**to pass in its own dictionary. The next section shows this.
Because it is a plain dictionary, every dictionary tool applies: len(kwargs), "key" in kwargs, kwargs.get("key", default), kwargs.pop("key"), and sorting its keys.
Mutating kwargs does not affect the caller
When a caller unpacks a dictionary with **, Python builds a new dictionary for the function's kwargs. The original is untouched.
def add_flag(**kwargs):
kwargs["debug"] = True
return kwargs
original = {"name": "x"}
result = add_flag(**original)
print(original) # {'name': 'x'}
print(result) # {'name': 'x', 'debug': True}
print(result is original) # FalseThis copy is shallow. The values are the same objects the caller holds. If a value is a list and you append to it inside the function, the caller sees the change. Only the dictionary container is new.
Mixing named parameters with **kwargs
Most real functions have some required parameters and accept extra keywords beyond them. Named parameters come first, and **kwargs goes last.
def make_tag(name, **attrs):
parts = [f'{key}="{value}"' for key, value in attrs.items()]
if parts:
return f"<{name} {' '.join(parts)}>"
return f"<{name}>"
print(make_tag("a", href="/home", title="Home"))
# <a href="/home" title="Home">
print(make_tag("br"))
# <br>Python matches each keyword argument to a named parameter first. Only the leftovers go into attrs. In the first call, name receives "a" positionally, and href and title have no matching parameter, so they land in attrs.
The diagram shows the decision Python makes for each keyword argument in a call.
Keys do not have to be valid identifiers
When you write make_tag("a", href="/home"), the keyword must be a valid Python name. class is a reserved word, so make_tag("div", class="box") is a syntax error. A dictionary has no such restriction, and a function with **kwargs accepts any string key that arrives through **.
print(make_tag("div", **{"class": "box"}))
# <div class="box">
print(make_tag("div", **{"data-id": "7"}))
# <div data-id="7">This is useful for building HTML attributes or handling keys read from a file. Keys must still be strings. Passing **{1: "x"} raises a TypeError.
Reading options with defaults
A common use of **kwargs is a set of optional settings. There are two ways to read one. kwargs.get(name, default) reads a value and leaves it in the dictionary. kwargs.pop(name, default) reads it and removes it.
The pop form lets you detect leftovers, meaning options the caller passed that the function does not recognize.
def connect(host, **options):
timeout = options.pop("timeout", 10)
retries = options.pop("retries", 3)
if options:
unknown = ", ".join(sorted(options))
raise TypeError(f"connect() got unexpected options: {unknown}")
return host, timeout, retries
print(connect("db.local"))
# ('db.local', 10, 3)
print(connect("db.local", timeout=5))
# ('db.local', 5, 3)
try:
connect("db.local", tmeout=5)
except TypeError as error:
print(error)
# connect() got unexpected options: tmeoutAfter the known options are popped, anything still in options is unrecognized. Raising TypeError copies how Python reports unknown keywords on ordinary functions, so callers see familiar behavior.
For a fixed set of options, though, plain named parameters with defaults are better. def connect(host, timeout=10, retries=3) gives you the same behavior, with the unknown-name check, documentation, and tooling support for free. Use **kwargs when the set of names is open-ended or when you are passing the names along.
Forwarding keywords to another function
The strongest reason to use **kwargs is to pass options through to something else without listing them. The function collects the extras and hands them on with **.
def render(text, *, bold=False, color="black"):
return f"{text} bold={bold} color={color}"
def warn(text, **style):
return render(text.upper(), **style)
print(warn("careful", color="red"))
# CAREFUL bold=False color=redwarn does not need to know which style options render supports. If render gains a new option later, warn supports it without a change. The later chapter on wrappers and decorators builds on this pattern.
The trade-off is that mistakes surface in the inner function, not at the outer one.
try:
warn("careful", colour="red")
except TypeError as error:
print(error)
# render() got an unexpected keyword argument 'colour'The error names render(), not warn(). This is correct, since render is where the bad keyword was rejected, but it can confuse a reader who only called warn. Document in the outer function which function receives the extra keywords.
Common errors and surprises
The table lists what happens in the situations that trip people up most often.
| Situation | Result |
|---|---|
| Misspelled keyword, function has `**kwargs` | Accepted silently and stored under the wrong name |
| Misspelled keyword, no `**kwargs` | `TypeError: ... got an unexpected keyword argument` |
| Same name passed positionally and as a keyword | `TypeError: ... got multiple values for argument` |
| Non-string key in a `**` dictionary | `TypeError` |
| Same key twice in one call, such as `f(a=1, **{"a": 2})` | `TypeError: ... got multiple values for keyword argument` |
Silent typos
The first row is the largest practical cost of **kwargs. A function with def connect(host, timeout=10) rejects tmeout=5 immediately. A function that reads kwargs.get("timeout", 10) accepts it, ignores it, and uses the default. The caller believes the timeout is 5 seconds, and it is not. Popping known options and rejecting leftovers, as connect did above, removes this risk.
A named parameter wins over the same key
If a name matches a parameter, it never reaches kwargs. Passing the same name twice is an error.
def f(a, **kw):
return a, kw
print(f(1, b=2)) # (1, {'b': 2})
try:
f(1, a=2)
except TypeError as error:
print(error) # f() got multiple values for argument 'a'If you want a function to accept a keyword called a inside kwargs while also having a parameter called a, make the parameter positional-only with /. Then the name a is free to appear as a keyword.
def f(a, /, **kw):
return a, kw
print(f(1, a=2)) # (1, {'a': 2})The chapter on keyword-only and positional-only parameters covers this syntax in full. The point here is that **kwargs collects names the signature cannot claim as keywords.
Duplicate keys across two sources
A call can mix explicit keywords and ** dictionaries. If the same name appears in more than one place, Python raises a TypeError instead of picking a winner.
def greet(name):
return f"Hello, {name}"
data = {"name": "Bob"}
print(greet(**data)) # Hello, Bob
try:
greet("Ada", **data)
except TypeError as error:
print(error) # greet() got multiple values for argument 'name'This differs from merging dictionaries with {**a, **b}, where the later key silently wins. To let one source override another in a call, merge first and then unpack the result: greet(**{**defaults, **overrides}).
Reading a required keyword
Unlike a named parameter, a keyword inside kwargs has no signature to enforce that it exists. Writing kwargs["timeout"] raises KeyError if the caller omitted it, and the message does not say which function was being called. If a keyword is required, make it a named parameter. Python then produces the clear message missing 1 required positional argument or its keyword-only equivalent.
How **kwargs relates to *args
The two collectors are independent. *args gathers extra positional values into a tuple. **kwargs gathers extra keyword values into a dictionary. A function can have either, both, or neither. When both are present, **kwargs must come last in the signature, and a later chapter covers the full ordering rules.
def describe(*args, **kwargs):
return f"{len(args)} positional, {len(kwargs)} keyword"
print(describe()) # 0 positional, 0 keyword
print(describe(1, 2, x=3)) # 2 positional, 1 keywordSummary of behavior
**kwargscollects keyword arguments that match no named parameter into a newdict.- It is empty, never
None, when no extras are passed, and it keeps call order. - Changing it inside the function does not change the caller's dictionary, though the values are shared.
- It accepts string keys that are not valid identifiers when they arrive through
**. - It hides misspelled names unless you check the leftovers or forward them to a function that does.
- Use named parameters when the names are known. Use
**kwargswhen names are open-ended or being forwarded.
Exercise
What does this code print, and why? def f(a, **kw): return a, kw print(f(a=1, b=2))
Show answer
It prints (1, {'b': 2}). The keyword a matches the named parameter a, so it is bound there and never reaches kw. Only b has no matching parameter, so it is the only entry in kw.
Exercise
Write a function buildurl(base, **params) that returns base followed by "?" and the parameters joined as key=value pairs with "&", in the order they were passed. If no parameters are passed, it should return base unchanged. For example, buildurl("http://x.io", page=2, sort="new") returns "http://x.io?page=2&sort=new".
Show answer
def buildurl(base, **params): if not params: return base query = "&".join(f"{key}={value}" for key, value in params.items()) return f"{base}?{query}" print(buildurl("http://x.io", page=2, sort="new")) # http://x.io?page=2&sort=new print(build_url("http://x.io")) # http://x.io
Exercise
The function below is meant to accept only the options "sep" and "end". A caller writes fmt(1, 2, sepp="-"). What happens, and how would you change the function so the typo is reported? def fmt(items, *options): sep = options.get("sep", " ") end = options.get("end", "") return sep.join(str(i) for i in items) + end
Show answer
Nothing is reported. The misspelled sepp is accepted into options, ignored, and the default separator is used, so the call returns "1 2". To report the typo, use pop instead of get, then raise TypeError if options is not empty. Better still, since the names are known, replace *options with keyword-only parameters: def fmt(items, sep=" ", end=""). Python then rejects sepp automatically.