Back to series
· 7 min read

Python Positional-Only and Keyword-Only Parameters


1. Why Are Parameter Passing Restrictions Needed?

In Python, function parameters can usually be passed in two ways: by position or by keyword.

def create_user(name, age):
    print(name, age)


# Pass by position
create_user("Alice", 25)

# Pass by keyword
create_user(name="Alice", age=25)

This flexibility is convenient, but not all parameters are suitable for supporting both passing styles at the same time.

For example:

def calculate_price(price, discount):
    return price * (1 - discount)

The caller can write it like this:

calculate_price(100, 0.2)

Or like this:

calculate_price(price=100, discount=0.2)

However, for some parameters, developers may want:

  • Parameters that can be passed only by position, preventing callers from relying on parameter names.
  • Parameters that can be passed only by keyword, improving the readability of calling code.
  • Parameter names that can be changed inside the function without affecting external calls.
  • A clear parameter interface that reduces misuse and ambiguity.

Python provides two parameter qualifiers:

Qualifier Purpose
/ Restricts the parameters to its left to being passed only by position
* Restricts the parameters to its right to being passed only by keyword

Together, they form an important part of Python function parameter signatures.

2. Positional-Only Parameters: /

1. Basic Syntax

In a function definition, use / to divide the parameter list into two regions.

Parameters to the left of / can be passed only by position, not by keyword.

def function(a, b, /, c, d):
    print(a, b, c, d)

Where:

  • a, b: positional-only parameters.
  • c, d: parameters that can be passed by position or keyword.
  • /: positional-only marker; it is not a parameter itself.

Call examples:

# Correct: all arguments passed by position
function(1, 2, 3, 4)

# Correct: the first two are passed by position, the last two by keyword
function(1, 2, c=3, d=4)

# Correct: all arguments passed by position
function(1, 2, d=4, c=3)

The following call will raise an error:

# Error: a is a positional-only parameter
function(a=1, b=2, c=3, d=4)

The reason is that a and b are to the left of / and cannot be passed using keyword form.

2. Why Are Positional-Only Parameters Needed?

The core value of positional-only parameters is that they let callers rely only on argument position, not on parameter names.

For example:

def divide(number, divisor, /):
    return number / divisor

Call:

divide(10, 2)

If the parameter names are adjusted inside the function in the future:

def divide(value, denominator, /):
    return value / denominator

The existing calling code still works:

divide(10, 2)

because the caller relies only on argument position and not on names such as number and divisor.

This is especially valuable for public APIs and third-party libraries.

3. Typical Use Cases for Positional-Only Parameters

Case 1: Parameter names are not part of the public interface

When parameter names are merely implementation details inside the function, you can use /.

def add(x, y, /):
    return x + y

Callers only need to know the order of the two arguments; they do not need to depend on the names x and y.

Case 2: Avoid keyword argument ambiguity

def process(data, /, mode="normal"):
    print(data, mode)

Here, data must be passed by position, while mode can be passed by keyword.

process([1, 2, 3], mode="fast")

This design clearly distinguishes core inputs from configurable options.

Scenario 3: Compatibility with Existing Calling Interfaces

If a function's parameter names may change in the future while their positions and semantics stay the same, positional-only parameters can reduce the compatibility problems caused by interface changes.

III. Keyword-Only Parameters: *

1. Basic Syntax

In a function definition, a standalone * restricts the parameters to its right so that they become keyword-only parameters.

def function(a, b, *, c, d):
    print(a, b, c, d)

Where:

  • a, b: can be passed positionally or by keyword.
  • c, d: can only be passed by keyword.
  • *: the keyword-only marker; it is not itself a parameter.

Correct calls:

# Correct: a and b passed positionally, c and d passed by keyword
function(1, 2, c=3, d=4)

# Correct: all arguments passed by keyword
function(a=1, b=2, c=3, d=4)

# Correct: the order of keyword arguments can be changed
function(1, 2, d=4, c=3)

Incorrect call:

# Incorrect: c and d cannot be passed positionally
function(1, 2, 3, 4)

2. Why Are Keyword-Only Parameters Needed?

The core value of keyword-only parameters is this: they make the caller state explicitly what each argument means.

For example:

def connect(host, port, *, timeout=30, retry=True):
    print(host, port, timeout, retry)

Call:

connect(
    "localhost",
    8080,
    timeout=10,
    retry=False
)

Without *, a caller might write this:

connect("localhost", 8080, 10, False)

Although the code is valid, it is not easy to tell at a glance what 10 and False stand for.

With the keyword-only restriction in place, the caller must write out the parameter names explicitly.

connect(
    "localhost",
    8080,
    timeout=10,
    retry=False
)

This makes the code more intuitive and also reduces the risk of mistakes caused by changes in argument order.

3. Typical Scenarios for Keyword-Only Parameters

Scenario 1: Configuration-style parameters

def create_file(path, *, encoding="utf-8", overwrite=False):
    print(path, encoding, overwrite)

Call:

create_file(
    "data.txt",
    encoding="utf-8",
    overwrite=True
)

The file path is the main input, while the encoding and the overwrite policy are configuration options.

Scenario 2: Boolean switch parameters

def send_message(message, *, async_mode=False, urgent=False):
    print(message, async_mode, urgent)

Call:

send_message(
    "系统通知",
    async_mode=True,
    urgent=False
)

If boolean arguments are passed positionally, it is hard for the caller to quickly judge what they mean.

Scenario 3: Avoiding argument-order mistakes

def create_user(name, *, active=True, admin=False):
    print(name, active, admin)

Call:

create_user(
    "Alice",
    admin=True,
    active=False
)

Even if the order of the keyword arguments is changed, their actual meaning does not change.

IV. Using / and * Together

Positional-only parameters and keyword-only parameters can appear together in the same function signature.

def function(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

The parameters are then divided into three regions:

Parameter region Parameter Passing method
Left of / a, b Positional only
Between / and * c, d Positional or keyword
Right of * e, f Keyword only

Example calls:

# Correct: mixed passing
function(1, 2, 3, 4, e=5, f=6)

# Correct: middle parameters passed by keyword
function(1, 2, d=4, c=3, e=5, f=6)

# Correct: all parameters that permit keywords are passed by keyword
function(1, 2, c=3, d=4, e=5, f=6)

Incorrect examples:

# Incorrect: a and b cannot be passed by keyword
function(a=1, b=2, c=3, d=4, e=5, f=6)

# Incorrect: e and f cannot be passed positionally
function(1, 2, 3, 4, 5, 6)

1. Complete parameter region diagram

def function(a, b, /, c, d, *, e, f):
                 │          │
                 │          └── keyword-only region
                 │              e and f can only use keywords
                 │
                 └── positional-only region
                     a and b can only use positional

Middle region:
c and d can be passed positionally or by keyword

2. Practical example of combined use

Design a user registration function:

def register_user(
    username,
    password,
    /,
    email,
    *,
    role="user",
    active=True
):
    return {
        "username": username,
        "password": password,
        "email": email,
        "role": role,
        "active": active
    }

Call:

user = register_user(
    "alice",
    "123456",
    "alice@example.com",
    role="admin",
    active=True
)

Parameter design rationale:

  • username, password: Core identity information, positional only.
  • email: Can be passed positionally or by keyword.
  • role, active: Configuration attributes, must be passed by keyword.

This design separates core parameters from configuration parameters, making the function interface clearer.

V. Difference Between Parameter Qualifiers and args,*kwargs

Beginners often confuse a standalone *, *args, and **kwargs.

They do not serve the same purpose.

1. Standalone *

A standalone * is used to separate parameter regions and restrict the parameters on its right so they can only be passed by keyword.

def function(a, *, b):
    print(a, b)

Call:

function(1, b=2)

2. *args

*args is used to receive any number of positional arguments and collect them into a tuple.

def function(a, *args):
    print(a)
    print(args)

Call:

function(1, 2, 3, 4)

Output:

1
(2, 3, 4)

*args is not just a parameter separator; it is itself a formal parameter that can receive multiple positional arguments.

3. **kwargs

**kwargs is used to receive extra keyword arguments and collect them into a dictionary.

def function(**kwargs):
    print(kwargs)

Call:

function(name="Alice", age=25)

Output:

{'name': 'Alice', 'age': 25}

4. Comparison of the Three

Syntax Purpose Whether It Accepts Arguments Result
/ Restricts parameters on the left to positional passing only No Parameter-passing rule
* Restricts parameters on the right to keyword passing only No Parameter-passing rule
*args Collects extra positional arguments Yes Tuple
**kwargs Collects extra keyword arguments Yes Dictionary

Note:

*args also creates a positional-parameter separator effect. Ordinary formal parameters after *args can only be passed by keyword.

def function(a, *args, b):
    print(a, args, b)

Call:

function(1, 2, 3, b=4)

Output:

1 (2, 3) 4

Here, b is a keyword-only parameter and is not part of args.

VI. Complete Classification of Python Function Parameters

Together, /, *, *args, and **kwargs provide a more complete understanding of Python's function parameter system.

1. Five Common Parameter Types

Parameter Type Definition Syntax Call Syntax
Positional-only parameters a, / Can only be passed positionally
Positional-or-keyword parameters a Can be passed positionally or by keyword
Variadic positional parameters *args Accepts multiple positional arguments
Keyword-only parameters *, b Can only be passed by keyword
Variadic keyword parameters **kwargs Accepts multiple keyword arguments

2. Complete Parameter Signature Example

def function(
    a,
    b,
    /,
    c,
    d=10,
    *args,
    e,
    f=20,
    **kwargs
):
    print(a, b, c, d)
    print(args)
    print(e, f)
    print(kwargs)

Parameter breakdown:

Parameter Type Description
a, b Positional-only parameters Can only be passed positionally
c Positional-or-keyword parameter Can be passed either way
d Positional-or-keyword parameter with a default value Can be omitted
args Variadic positional parameter Collects extra positional arguments
e Keyword-only parameter Must be passed as a keyword argument
f Keyword-only parameter with a default value Can be omitted
kwargs Variadic keyword parameter Collects extra keyword arguments

Call:

function(
    1,
    2,
    3,
    4,
    5,
    6,
    e=7,
    f=8,
    name="Alice",
    age=25
)

Output:

1 2 3 4
(5, 6)
7 8
{'name': 'Alice', 'age': 25}

The parameter binding process here can be understood as follows:

Receive function call
    |
    v
Bind positional arguments
    |
    v
Bind positional-or-keyword parameters
    |
    v
Collect extra positional arguments into args
    |
    v
Bind keyword-only parameters
    |
    v
Collect extra keyword arguments into kwargs
    |
    v
Check whether required parameters are missing
    |
    v
Execute function body

If parameter binding fails, Python raises a TypeError before executing the function body.

7. Parameter Binding Rules and Common Errors

To understand parameter qualifiers, you also need to master Python's parameter binding rules.

1. The same parameter cannot be assigned twice

def greet(name, /):
    print(name)

Call:

greet("Alice")

Correct.

Since name is a positional-only parameter, the following call raises an error:

greet("Alice", name="Bob")

This is because the positional argument has already bound name, while at the same time an attempt is made to pass the same parameter by keyword.

2. Keyword-only parameters cannot be omitted

def create_user(name, *, age):
    print(name, age)

Call:

create_user("Alice")

This raises an error, because the required parameter age was not passed.

Correct call:

create_user("Alice", age=25)

3. The order of keyword arguments can be rearranged

def connect(host, *, port, timeout):
    print(host, port, timeout)

Both of the following calls are correct:

connect("localhost", port=8080, timeout=10)

connect("localhost", timeout=10, port=8080)

Keyword arguments are bound by name and do not depend on the order in which they are passed.

4. Default values and parameter qualifiers are independent of each other

Whether a parameter's passing style is qualified and whether a parameter has a default value are two separate issues.

def function(a, /, b=10, *, c=20):
    print(a, b, c)

Here:

  • a: positional-only and required.
  • b: can be passed positionally or by keyword, and has a default value.
  • c: keyword-only, and has a default value.

Call:

function(1)

function(1, 2)

function(1, b=2, c=3)

All are valid.

5. Positional-only parameters cannot come after keyword arguments

For example:

def function(a, /, b):
    print(a, b)

The following call is correct:

function(1, b=2)

The following call is incorrect:

function(a=1, b=2)

Because a must be passed positionally.

8. How Do You Inspect a Function's Parameter Qualification Rules?

Python provides the inspect standard library, which lets you inspect function signatures and parameter types.

1. Using inspect.signature()