Lesson 6 of 16 · Functions in Depth
Args and Kwargs
Understand *args and **kwargs in Python: write functions that accept any number of arguments, pass options through to other functions and read real library code.
- 7 min read
- Intermediate
- Reviewed
- How to accept any number of positional arguments with *args
- How to accept any number of named arguments with **kwargs
- The order parameters must appear in
- How to pass arguments on to another function
Any number of values
print() accepts one value, three values or twenty. How can a function take "any number" of arguments? With a star in front of a parameter.
def total(*numbers):
print(numbers)
return sum(numbers)
print(total(5))
print(total(5, 10, 20))
print(total())*numbers collects all the positional arguments into a tuple. The function can then loop over it, count it or add it up, like any tuple.
The name after the star can be anything. By tradition it is often args, short for "arguments", which is why you will see *args everywhere.
A more useful example
def average(*values):
if not values:
return 0
return sum(values) / len(values)
print(average(70, 80, 90))
print(average(55))
print(average())Required arguments first, then the rest
Normal parameters can come before *args. They are filled first, and the star collects whatever is left.
def log(level, *messages):
print(f"[{level}]", " ".join(messages))
log("INFO", "Training", "started")
log("ERROR", "Out", "of", "memory")Any number of named values: **kwargs
Two stars collect keyword arguments into a dictionary. The traditional name is kwargs, short for "keyword arguments".
def describe(**details):
print(details)
for key, value in details.items():
print(f"{key}: {value}")
describe(name="Ada", role="engineer", city="London")Each name=value in the call becomes one entry in the dictionary.
The full order
A function can use all of these at once. They must appear in this order:
def example(required, optional="default", *args, **kwargs):
...- Normal parameters
- Parameters with defaults
*args**kwargs
def show(title, *items, separator=", ", **extras):
print(title + ":", separator.join(items))
if extras:
print("Extras:", extras)
show("Fruits", "apple", "banana")
show("Tools", "Python", "SQL", separator=" | ", level="beginner")separator comes after *items, so it can only be passed by name. That makes it a keyword-only argument, exactly like the ones you met in the last lesson.
Passing arguments on
The most common real use of *args and **kwargs is to pass everything through to another function without listing each argument. You use the same stars to spread them back out.
def generate(prompt, temperature=0.7, max_tokens=100):
return f"'{prompt}' at temperature {temperature}, up to {max_tokens} tokens"
def generate_and_log(*args, **kwargs):
print("Calling generate with", args, kwargs)
return generate(*args, **kwargs)
print(generate_and_log("Write a haiku", temperature=0.2))generate_and_log does not need to know which settings generate accepts. If generate gains a new option later, the wrapper still works.
Common mistakes
Use *classes and **attributes to build an HTML tag from any number of classes and attributes.
# Write a function called build_tag(name, *classes, **attributes)
# that returns an HTML opening tag as text:
# - classes are joined with spaces into class="..."
# - every attribute becomes key="value"
# Hint for the quotes: f'{key}="{value}"'
print(build_tag("button", "btn", "primary", type="submit"))
# Output must be exactly:
# <button class="btn primary" type="submit">
Inside def f(*args, **kwargs), what is kwargs when you call f(1, 2, mode='fast')?
Summary
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.- Order: normal parameters, defaults,
*args,**kwargs. f(*args, **kwargs)spreads them back out to pass everything on to another function.
Next: small functions written in a single line.
Finished reading? Tick it off to track your progress.