Arguments
Functions and modules5 min readLesson 1 of 3
Minutes: 5
Positional arguments are matched by order; keyword arguments by name.
python
def move(x, y=0):
return (x, y)
move(3) # (3, 0)
move(3, y=5) # (3, 5)
move(y=5, x=3) # (3, 5)A default is evaluated once, when the function is defined. Never use a mutable default like []; it is shared across calls.
python
def add_item(item, bucket=None):
bucket = [] if bucket is None else bucket
bucket.append(item)
return bucketFor a function that accepts anything, collect the rest:
python
def total(*numbers):
return sum(numbers)
def tag(**labels):
return labelsKeep functions small enough that the call site reads like a sentence.
