We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Args and Kwargs

In Python, *args and **kwargs allow a function to accept and deal with a variable number of arguments.

  • *args collects positional arguments into a tuple
  • **kwargs collects keyword (named) arguments into a dictionary
def print_arguments(*args: object, **kwargs: object) -> None:
    print(f"Positional arguments: {args}")
    print(f"Keyword arguments: {kwargs}")


print_arguments("hello", "world", a=1, b=2)
# Positional arguments: ('hello', 'world')
# Keyword arguments: {'a': 1, 'b': 2}

Positional Arguments

Positional arguments are the ones you're already familiar with, where the order of the arguments matters. Like this:

def sub(a: int, b: int) -> int:
    return a - b


# a=3, b=2
res: int = sub(3, 2)
# res = 1

Keyword Arguments

Keyword arguments are passed in by name. Order does not matter. Like this:

def sub(a: int, b: int) -> int:
    return a - b


res: int = sub(b=3, a=2)
# res = -1
res = sub(a=3, b=2)
# res = 1

A Note on Ordering

Any positional arguments must come before keyword arguments. This will not work:

sub(b=3, 2)

Assignment

At Doc2Doc, we need better internal debugging tools. Complete the args_logger function. It takes a variable number of positional and keyword arguments and prints them to the console.

  1. args_logger("what's", "up", "doc")
    

    prints to the console:

    1. what's
    2. up
    3. doc
    
  2. args_logger("hi", "there", age=17, date="July 4 1776")
    

    prints to the console:

    1. hi
    2. there
    * age: 17
    * date: July 4 1776
    

Tips

  • Don't feel guilty about using loops.
  • kwargs is a dictionary, not a list. My recommendation is to use the .items() method to get the key-value pairs as a list of tuples, then sort that list before printing.
  • When you call sorted on a list of tuples, by default it sorts by the first item in each tuple (which is what you want here).