2.3. Parameter Syntax

def echo(a, b, c=3):
     print(a, b, c)

echo(1, 2)              # 1 2 3
echo(1, b=2)            # 1 2 3
echo(1, c=3)            # TypeError: echo() missing 1 required positional argument: 'b'
echo(1, 2, 3)           # 1 2 3
echo(1, 2, c=3)         # 1 2 3
echo(1, b=2, c=3)       # 1 2 3
echo(a=1, b=2, c=3)     # 1 2 3

2.3.1. Keyword-only parameters

  • All parameters after * must be keyword-only

def echo(a, *, b, c=3):
    print(a, b, c)

echo(1, 2)              # TypeError: echo() takes 1 positional argument but 2 were given
echo(1, b=2)            # 1 2 3
echo(1, c=3)            # TypeError: echo() missing 1 required keyword-only argument: 'b'
echo(1, 2, 3)           # TypeError: echo() takes 1 positional argument but 3 were given
echo(1, 2, c=3)         # TypeError: echo() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
echo(1, b=2, c=3)       # 1 2 3
echo(a=1, b=2, c=3)     # 1 2 3

2.3.2. Positional-only parameters

New in version Python: 3.8 See PEP 570 Python Positional-Only Parameters

  • All parameters before / must be positional-only

def echo(a, /, b, c=3):
    print(a, b, c)

echo(1, 2)              # 1 2 3
echo(1, b=2)            # 1 2 3
echo(1, c=3)            # TypeError: echo() missing 1 required positional argument: 'b'
echo(1, 2, 3)           # 1 2 3
echo(1, 2, c=3)         # 1 2 3
echo(1, b=2, c=3)       # 1 2 3
echo(a=1, b=2, c=3)     # TypeError: echo() got some positional-only arguments passed as keyword arguments: 'a'

2.3.3. Positional and Keyword parameters

def echo(a, /, b, *, c=3):
    print(a, b, c)

echo(1, 2)              # 1 2 3
echo(1, b=2)            # 1 2 3
echo(1, c=3)            # TypeError: echo() missing 1 required positional argument: 'b'
echo(1, 2, 3)           # TypeError: echo() takes 2 positional arguments but 3 were given
echo(1, 2, c=3)         # 1 2 3
echo(1, b=2, c=3)       # 1 2 3
echo(a=1, b=2, c=3)     # TypeError: echo() got some positional-only arguments passed as keyword arguments: 'a'

2.3.4. Examples

def pow(x, y, z=None, /):
    ...
def quantiles(dist, /, *, n=4, method='exclusive')
    ...
def add(a, b, /, **kwargs):
   ...