Gavin Wiggins

Asterisk and Slash in Python Function Parameters

In a Python function definition, * and / separate parameters into groups. Neither symbol takes a value. The table below summarizes the effects of these symbols. Examples are given in the following sections.

DefinitionParameter aParameter b
f(a, *, b)By position or keywordBy keyword only
f(a, /, b)By position onlyBy position or keyword

Asterisk

A bare * makes the parameters after it keyword-only. Here, spelling out uppercase=True tells the reader what the flag does. The name parameter comes before *, so it can be passed by position or by keyword.

def username(name, *, uppercase=False):
    return name.upper() if uppercase else name.lower()


username("Ada", uppercase=True)  # 'ADA'
username(name="Ada")             # 'ada'
# username("Ada", True)          # TypeError: uppercase must be named

Slash

In Python 3.8 and later, / makes the parameters before it positional-only. With the slash at the end, the first argument supplies first and the second supplies last. Neither parameter name is part of the calling interface, so renaming one won't break callers.

def username(first, last, /):
    return (first[0] + last).lower()


username("Ada", "Lovelace")           # 'alovelace'
# username("Ada", last="Lovelace")    # TypeError: last is positional-only

Move / between first and last, and only first remains positional-only. Now the caller can pass last either by position or by keyword.

def username(first, /, last):
    return (first[0] + last).lower()


username("Ada", "Lovelace")            # 'alovelace'
username("Ada", last="Lovelace")       # 'alovelace'
# username(first="Ada", last="Lovelace")  # TypeError: first is positional-only

Slash and asterisk

When both markers appear, / comes first. Read the signature from left to right: name must be passed by position, suffix can be passed either way, and uppercase must be named if supplied. The two calls below differ only in how they pass the suffix.

def username(name, /, suffix, *, uppercase=False):
    handle = name + suffix
    return handle.upper() if uppercase else handle.lower()


username("Ada", "42", uppercase=True)         # 'ADA42'
username("Ada", suffix="42", uppercase=True)  # 'ADA42'
# username("Ada", "42", True)                # TypeError: uppercase must be named