The / and * Syntax in Python Function Parameters
Python lets you control how function arguments must be passed using / and * in the parameter list:
def foo(arg1, /, arg2, *, arg3):
print(arg1, arg2, arg3)What They Mean
- Parameters before
/are positional-only - Parameters after
*are keyword-only - Parameters in between can be either
Why It Matters
This is especially useful for library authors. It lets you maintain control over how your function is called, so you can rename parameters later without breaking existing code.
Example
def calculate(x: int, y: int, /, *, method: str) -> None:
if method != "multiply":
raise ValueError("This calculator supports only multiplication. 🫣")
print(f"{x} × {y} = {x * y}")Here x and y must be positional, and method must be a keyword argument:
>>> calculate(1, 2, "multiply")
TypeError: calculate() takes 2 positional arguments but 3 were given
>>> calculate(x=2, y=3, method="multiply")
TypeError: calculate() got some positional-only arguments
passed as keyword arguments: 'x, y'
>>> calculate(2, 3, method="multiply")
2 × 3 = 6