

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Decorators
incomplete
2: Args and Kwargs
incomplete
3: Args and Kwargs Practice
incomplete
4: Decorators
incomplete
5: Decorators Review
incomplete
6: LRU Cache
incomplete
7: Decorators Practice
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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 dictionarydef 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 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 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
Any positional arguments must come before keyword arguments. This will not work:
sub(b=3, 2)
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.
args_logger("what's", "up", "doc")
prints to the console:
1. what's
2. up
3. doc
args_logger("hi", "there", age=17, date="July 4 1776")
prints to the console:
1. hi
2. there
* age: 17
* date: July 4 1776
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.sorted on a list of tuples, by default it sorts by the first item in each tuple (which is what you want here).