Named extras: **kwargs
🌍 In real life. A form has boxes for "Name" and "Phone", plus a big box at the bottom: "Anything else? (write label: value)". People write things like "allergy: peanuts" or "floor: 3rd". The office keeps those extra labelled notes together, even though the form never knew which labels would come.
Two stars give a function that "anything else" box.
The idea in one sentence: a parameter like **extra collects the extra keyword arguments, the named ones with no parameter of their own, into a dictionary.
Its words:
**kwargs: a double-starred parameter;kwargsis the usual name- extra keyword argument:
city="Dhaka"when there's nocityparameter - unpacking a dict in a call:
f(**settings)turns each key into a keyword argument - the order: normal parameters, then
*args, then**kwargs
Step by step, for profile("Ana", age=9, city="Dhaka"):
nametakes the first value,"Ana".ageandcityhave no parameters of their own.**extracollects them:{'age': 9, 'city': 'Dhaka'}.
def profile(name, **extra):
print(name)
for key, value in extra.items():
print(" ", key, "=", value)
profile("Ana", age=9, city="Dhaka")
profile("Bo")Everything together, in this order: normal parameters, *args, then **kwargs. Each argument goes to the first place that fits:
def f(a, b=2, *rest, **opts):
print(a, b, rest, opts)
f(1)
f(1, 5, 6, x=9)In a call, **my_dict spreads a dictionary out into keyword arguments:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
settings = {"name": "Cy", "greeting": "Hi"}
print(greet(**settings))When is it useful? When a function passes options on to another function, or accepts settings it doesn't need to list one by one. Use it sparingly: named parameters show the reader exactly what a function accepts, while **kwargs hides it.
Mistakes and edge cases.
- A parameter after **kwargs.
def f(**k, a):givesSyntaxError: arguments cannot follow var-keyword argument. It must be last. - A positional value for **kwargs.
**optsonly collects named values:f(1)fordef f(**o):givesTypeError: f() takes 0 positional arguments but 1 was given. - A key that's no parameter.
greet(**{"nam": "Cy"})fails like a misspelt keyword:unexpected keyword argument 'nam'. - Keys must be strings.
f(**{1: "a"})is a TypeError: keyword names are always text.
Quiz
What does this print?
def opts(**k): return k print(opts(a=1, b=2))What does this print?
def f(x, **rest): print(x, rest) f(x=1, y=2)What does this print?
def size(**k): return len(k) print(size(), size(a=1, b=2, c=3))In what order must these parameter kinds be written?
- normal, *args, **kwargs
- **kwargs, *args, normal
- Any order works
Which line has a mistake?
def f(a): return a print(f(1, b=2))
Coding tasks
Write
make_profile(name, **extra)that returns a dictionary with"name"and all the extra named values.Write
count_options(**opts)that returns how many named arguments it was given.Write
order(item, *extras, **notes)that returns a tuple ofitem, the tuple of extras, and the dictionary of notes.