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 them with items(). It also assumes you have seen *args, which collects extra positional arguments.
What **kwargs collects
A function normally accepts only the keyword arguments it names in its signature. Adding **kwargs to the signature lets the function also accept any other keyword arguments. Python gathers them into a dictionary. Each argument name becomes a string key, and each value becomes the dictionary value.
def show(**kwargs):
for key, value in kwargs.items():
print(f"{key}={value}")
show(name="Ada", age=36)
# name=Ada
# age=36The name kwargs is a convention, short for "keyword arguments". The ** is what matters. You could write **options or **attrs, and a descriptive name is often better.
What the dictionary looks like
Inside the function, kwargs is an ordinary dict. It keeps the order in which the caller wrote the arguments. If the caller passes no extra keywords, it is an empty dictionary, never None.
def info(**kwargs):
print(type(kwargs))
kwargs["extra"] = True
print(kwargs)
info(a=1)
info()
# <class 'dict'>
# {'a': 1, 'extra': True}
# <class 'dict'>
# {'extra': True}The dictionary is created fresh on every call. Changing it does not affect any dictionary the caller used to build the arguments.
Mixing named parameters with **kwargs
Named parameters take their matching arguments first. Whatever is left over goes into kwargs. Here name is required, and every other keyword becomes an HTML attribute.
def make_tag(name, **attrs):
parts = [name]
for key, value in attrs.items():
parts.append(f'{key}="{value}"')
return "<" + " ".join(parts) + ">"
print(make_tag("a", href="https://example.com", title="Home"))
# <a href="https://example.com" title="Home">
print(make_tag("br"))
# <br>Note that name="a" would also work as a call, because name is a named parameter. It would not end up in attrs.
Reading values with defaults
Because kwargs is a dictionary, get() gives you an optional setting with a fallback value.
def connect(host, **options):
timeout = options.get("timeout", 30)
retries = options.get("retries", 3)
return f"{host} timeout={timeout} retries={retries}"
print(connect("db.local"))
# db.local timeout=30 retries=3
print(connect("db.local", retries=5))
# db.local timeout=30 retries=5This style is common for configuration-like functions. It has a cost, covered next: nothing checks the keys for you.
Typos are accepted silently
A function with **kwargs accepts any keyword name. If a caller misspells an option, no error is raised. The option is simply ignored.
print(connect("db.local", timout=5))
# db.local timeout=30 retries=3The misspelled timout went into options and was never read. If you only accept a known set of options, check for leftovers. Removing each known key with pop() makes the check easy.
def connect_strict(host, **options):
timeout = options.pop("timeout", 30)
retries = options.pop("retries", 3)
if options:
unknown = ", ".join(sorted(options))
raise TypeError(f"unexpected options: {unknown}")
return f"{host} timeout={timeout} retries={retries}"
try:
connect_strict("db.local", timout=5)
except TypeError as error:
print(error)
# unexpected options: timoutIf the set of options is small and fixed, ordinary named parameters with defaults are usually better. They give you the checking for free and show up in help text and editor hints.
What **kwargs does not accept
**kwargs collects only keyword arguments. A positional argument with no matching parameter is still an error.
def show(**kwargs):
print(kwargs)
try:
show(1)
except TypeError as error:
print(error)
# show() takes 0 positional arguments but 1 was givenTo accept extra positional values as well, add *args too. The rules for combining them are the subject of the next chapter.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Writing `def f(kwargs)` and calling `f(a=1)` | `TypeError`: unexpected keyword argument `a` | Use `def f(**kwargs)` |
| Writing `kwargs["x"]` when `x` may be missing | `KeyError` | Use `kwargs.get("x", default)` |
| Passing a dictionary as `f(d)` | The dictionary becomes one positional argument | Spread it with `f(**d)` |
| Expecting typos to fail | The misspelled key is silently stored | Check leftover keys, as in `connect_strict` |
Summary
**kwargscollects unmatched keyword arguments into a newdict.- Keys are the argument names as strings, and the dictionary is empty when none are passed.
- Named parameters are filled first, and
kwargsholds the rest. - Use
get()for optional settings andpop()when you want to detect unknown options. **kwargsnever absorbs positional arguments.
Exercise
Write a function describe(title, **details) that returns the title, then each detail as key: value, joined by ", ". For example, describe("Book", author="Le Guin", year=1969) returns Book, author: Le Guin, year: 1969. What does describe("Book") return?
Show answer
def describe(title, **details):
parts = [title]
for key, value in details.items():
parts.append(f"{key}: {value}")
return ", ".join(parts)
With no extra keywords, details is an empty dictionary, so the loop adds nothing and describe("Book") returns just "Book".
Exercise
Given def connect(host, **options) that reads options.get("timeout", 30), why does connect("db.local", timout=5) not raise an error, and how can the function be changed to reject it?
Show answer
**options accepts any keyword name, so timout is stored in options and never read. To reject it, remove each known key with options.pop(...), then raise TypeError if options still has any keys left.