*args and **kwargs in Python
Variadic functions: accepting any number of arguments.
def report(title, *values, **options):
sep = options.get("sep", ", ")
body = sep.join(str(v) for v in values)
line = f"{title}: {body}"
if options.get("upper"):
line = line.upper()
return line
plain = report("temps", 18, 21, 19)
loud = report("temps", 18, 21, upper=True)
numbers = [3, 1, 4, 1, 5]
spread = report("digits", *numbers, sep=" | ")
How it works
*valuescollects extra positional args into a tuple.**optionscollects extra keyword args into a dict.*numbersat the call site spreads a list back out.
Keywords and builtins used here
defforifreportreturnstr
The run, in numbers
- Lines
- 14
- Characters to type
- 347
- Tokens
- 133
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 84 seconds.
Step 2 of 6 in Functions, step 34 of 72 in Language basics.