TExcelTAD
Home › Python › Python Arguments

Python Arguments

Python gives you a lot of control over how a function receives its arguments. You've already seen positional arguments and default values; this lesson covers keyword arguments in depth, *args, **kwargs, unpacking, and the special / and * markers.

Positional vs keyword arguments

Positional arguments are matched to parameters by order. Keyword arguments are matched by name, so their order doesn't matter:

python · try it yourself
def describe_pet(name, species, age):
    return f"{name} is a {age}-year-old {species}"

print(describe_pet("Miu", "cat", 3))                    # positional
print(describe_pet(age=5, name="Lu", species="dog"))     # keyword
print(describe_pet("Bong", age=1, species="rabbit"))    # mixed
Miu is a 3-year-old cat
Lu is a 5-year-old dog
Bong is a 1-year-old rabbit

When mixing, positional arguments must come first. describe_pet(name="Lu", "dog", 5) is a SyntaxError.

*args — any number of positional arguments

Prefix a parameter with * and it collects all extra positional arguments into a tuple. The name args is just a convention:

python · try it yourself
def total(*numbers):
    print("received:", numbers)
    return sum(numbers)

print(total(1, 2, 3))
print(total(10))
print(total())
received: (1, 2, 3)
6
received: (10,)
10
received: ()
0

**kwargs — any number of keyword arguments

A parameter prefixed with ** collects extra keyword arguments into a dictionary:

python · try it yourself
def build_profile(username, **details):
    profile = {"username": username}
    profile.update(details)
    return profile

print(build_profile("thao"))
print(build_profile("long", city="Hue", job="designer"))
{'username': 'thao'}
{'username': 'long', 'city': 'Hue', 'job': 'designer'}

You can combine everything. The order in the definition must be: normal parameters, *args, keyword-only parameters, **kwargs:

python · try it yourself
def log(level, *messages, sep=" ", **meta):
    text = sep.join(messages)
    extra = ", ".join(f"{k}={v}" for k, v in meta.items())
    print(f"[{level}] {text} ({extra})")

log("INFO", "server", "started", port=8080, debug=False)
log("WARN", "disk", "almost", "full", sep="_", used="91%")
[INFO] server started (port=8080, debug=False)
[WARN] disk_almost_full (used=91%)

Unpacking arguments in a call

The same stars work in the other direction: * spreads a list or tuple into positional arguments, ** spreads a dict into keyword arguments:

python · try it yourself
def volume(length, width, height):
    return length * width * height

size = [2, 3, 4]
print(volume(*size))

dims = {"height": 10, "length": 1, "width": 5}
print(volume(**dims))

print(*["a", "b", "c"], sep="-")
24
50
a-b-c

Keyword-only and positional-only parameters

Anything after a bare * in the definition must be passed by keyword. Anything before a / (Python 3.8+) must be passed by position:

python · try it yourself
def connect(host, /, port=80, *, timeout=10):
    return f"{host}:{port} (timeout {timeout}s)"

print(connect("example.com"))
print(connect("example.com", 443, timeout=3))

try:
    connect("example.com", 443, 3)
except TypeError as err:
    print("Error:", err)
example.com:80 (timeout 10s)
example.com:443 (timeout 3s)
Error: connect() takes from 1 to 2 positional arguments but 3 were given

Keyword-only arguments make calls self-documenting: timeout=3 is much clearer than a bare 3.

Marker Meaning
def f(a, b) normal: by position or keyword
def f(*args) extra positional args → tuple
def f(**kwargs) extra keyword args → dict
def f(a, *, b) b is keyword-only
def f(a, /, b) a is positional-only

The mutable default trap

Default values are created once, when the function is defined — not on every call. A mutable default therefore remembers changes between calls:

python · try it yourself
def add_item_bad(item, basket=[]):
    basket.append(item)
    return basket

print(add_item_bad("egg"))
print(add_item_bad("milk"))     # surprise: the egg is still there

def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item("egg"))
print(add_item("milk"))
['egg']
['egg', 'milk']
['egg']
['milk']

Tip: Use None as the default for any parameter that should start as a fresh list, dict or set.

Test yourself

Inside def f(*args), what type is args?

  1. list
  2. tuple
  3. dict
  4. set

What does **kwargs collect?

  1. Extra positional arguments into a list
  2. Extra keyword arguments into a dict
  3. All arguments into a tuple
  4. Only default values

In def f(a, *, b):, how must b be passed?

  1. By position only
  2. By keyword only
  3. Either way
  4. It can't be passed