typestar

*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

  1. *values collects extra positional args into a tuple.
  2. **options collects extra keyword args into a dict.
  3. *numbers at the call site spreads a list back out.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 6 in Functions, step 34 of 72 in Language basics.

← Previous Next →