Skip to content

Python Keyword-Only Parameters: Clearer Calls (3.0+)

  • How the bare * and *args turn the parameters after them into keyword-only parameters.
  • Required keyword-only parameters, defaults in any order, and how to inspect them.
  • How dataclass(kw_only=True) and KW_ONLY apply the same rule to constructors.
  • How to migrate an existing positional parameter to keyword-only without breaking callers overnight.
  • When keyword-only parameters help and when they just add noise.

A keyword-only parameter can be filled only by a keyword argument, never by position. You declare one by placing it after a bare * or after a var-positional parameter such as *args. The feature arrived in Python 3.0 with PEP 3102 and is fully current in Python 3.14. It is the standard tool for option flags, configuration values and any argument whose meaning is not obvious from its position.

When every parameter can be passed by position, call sites fill up with unexplained literals. create_refund("ORD-1001", 25.0, False, True) compiles, runs and tells the reader nothing about which flag is which; swapping the two booleans is a silent bug. The function author is also stuck: inserting a new parameter in the middle, or reordering two flags, changes the meaning of existing positional calls.

The samples on this page are plain scripts: save each as a .py file and run it with python3 file.py. They were run on CPython 3.14.6 and the output shown is from that run.

# Before: every parameter can be passed by position.
def create_refund_v1(order_id, amount, notify_customer=False, restock=False):
return f"{order_id}: refund {amount} notify={notify_customer} restock={restock}"
# Which flag is which? The call site does not say, and swapping them is silent.
print(create_refund_v1("ORD-1001", 25.0, False, True))
# After: everything after the bare * must be passed by name.
def create_refund(order_id, amount, *, notify_customer=False, restock=False):
return f"{order_id}: refund {amount} notify={notify_customer} restock={restock}"
print(create_refund("ORD-1001", 25.0, restock=True))
try:
create_refund("ORD-1001", 25.0, False, True)
except TypeError as exc:
print("TypeError:", exc)

Output:

ORD-1001: refund 25.0 notify=False restock=True
ORD-1001: refund 25.0 notify=False restock=True
TypeError: create_refund() takes 2 positional arguments but 4 were given

The new call is self-describing, the caller can skip notify_customer entirely, and the old ambiguous call now fails loudly.

Python has five kinds of parameter: positional-only, positional-or-keyword, var-positional (*args), keyword-only and var-keyword (**kwargs). Everything after * or *args and before **kwargs is keyword-only.

PEP 3102 made two syntax changes. First, regular parameters may follow *args; they cannot be filled by position because *args absorbs all remaining positional arguments. Second, the name after * may be omitted, which means “accept no extra positional arguments here” and raises TypeError instead of silently collecting them.

import inspect
# 1. After a bare *: keyword-only, may be required (no default).
def ship_order(order_id, *, carrier, express=False):
return f"{order_id} via {carrier}{' (express)' if express else ''}"
print(ship_order("ORD-7", carrier="DHL"))
try:
ship_order("ORD-7")
except TypeError as exc:
print("TypeError:", exc)
# 2. After *args: also keyword-only, no bare * needed.
def tag_orders(*order_ids, tag, overwrite=False):
return [f"{oid}:{tag}" for oid in order_ids]
print(tag_orders("ORD-1", "ORD-2", tag="vip"))
# 3. Required keyword-only parameters may follow defaulted ones.
def export(*, fmt="csv", destination):
return f"{fmt} -> {destination}"
print(export(destination="s3://exports.example.test/daily"))
# 4. Introspection.
for name, p in inspect.signature(ship_order).parameters.items():
print(name, p.kind.name, p.default)
print(ship_order.__kwdefaults__)
# 5. Lambdas accept the same syntax.
fmt = lambda amount, *, currency="EUR": f"{amount:.2f} {currency}"
print(fmt(9.5), fmt(9.5, currency="USD"))

Output:

ORD-7 via DHL
TypeError: ship_order() missing 1 required keyword-only argument: 'carrier'
['ORD-1:vip', 'ORD-2:vip']
csv -> s3://exports.example.test/daily
order_id POSITIONAL_OR_KEYWORD <class 'inspect._empty'>
carrier KEYWORD_ONLY <class 'inspect._empty'>
express KEYWORD_ONLY False
{'express': False}
9.50 EUR 9.50 USD

Rules that follow from the specification:

  • Required keyword-only parameters have no default. The caller must name them, which is ideal for values that are mandatory but easy to confuse, like carrier.
  • Default ordering is relaxed. Among positional parameters a non-default cannot follow a default, but keyword-only parameters can appear in any order, as export(*, fmt="csv", destination) shows.
  • Defaults live separately. Keyword-only defaults are stored in __kwdefaults__, not __defaults__; inspect.signature() reports the kind as KEYWORD_ONLY.
  • A bare * needs at least one name after it. def f(a, *): is a SyntaxError: named arguments must follow bare *.
  • Unknown keywords fail. Without **kwargs, a misspelled keyword raises TypeError. Since Python 3.13 the message suggests the closest name.

The standard library uses the pattern heavily: sorted(iterable, /, *, key=None, reverse=False), dataclass(*, init=True, ...), map(..., strict=False) (Python 3.14) and zip(..., strict=False) (Python 3.10) all take their options by keyword only.

Since Python 3.10, @dataclass(kw_only=True) makes every field keyword-only in the generated __init__, field(kw_only=True) marks one field, and a pseudo-field annotated with KW_ONLY marks every field after it. Keyword-only fields are also excluded from __match_args__.

An OrdersPortal search function takes one obvious positional argument and a growing set of filters. The filters are keyword-only, so new ones can be added anywhere in the list without changing the meaning of existing calls, and the frozen query object enforces the same rule.

from dataclasses import KW_ONLY, dataclass
from datetime import date
@dataclass(frozen=True)
class OrderQuery:
customer_id: str # positional: obvious and always required
_: KW_ONLY # everything below must be named
status: str | None = None
since: date | None = None
page_size: int = 50
include_cancelled: bool = False
def search_orders(customer_id: str, *, status: str | None = None,
since: date | None = None, page_size: int = 50,
include_cancelled: bool = False) -> OrderQuery:
if not 1 <= page_size <= 500:
raise ValueError("page_size must be between 1 and 500")
return OrderQuery(customer_id, status=status, since=since,
page_size=page_size, include_cancelled=include_cancelled)
# Call sites read like a query string and survive parameter reordering.
q = search_orders("C-101", status="shipped", since=date(2026, 11, 1))
print(q)
# Options can be collected and forwarded as a dict.
filters = {"status": "pending", "page_size": 20}
print(search_orders("C-207", **filters))
# A typo in an option name fails loudly instead of being ignored.
try:
search_orders("C-207", page_sise=20)
except TypeError as exc:
print("TypeError:", exc)
# The dataclass constructor enforces the same rule.
try:
OrderQuery("C-101", "shipped")
except TypeError as exc:
print("TypeError:", exc)

Output:

OrderQuery(customer_id='C-101', status='shipped', since=datetime.date(2026, 11, 1), page_size=50, include_cancelled=False)
OrderQuery(customer_id='C-207', status='pending', since=None, page_size=20, include_cancelled=False)
TypeError: search_orders() got an unexpected keyword argument 'page_sise'. Did you mean 'page_size'?
TypeError: OrderQuery.__init__() takes 2 positional arguments but 3 were given

Turning an existing positional parameter into a keyword-only one breaks every caller that passes it by position. CPython itself handles this with a deprecation period: Python 3.13 deprecated passing maxsplit, count or flags positionally to re.split(), re.sub() and re.subn() before making them keyword-only. You can do the same with a small decorator that maps extra positional arguments onto the keyword-only names and warns.

import functools
import inspect
import warnings
def keyword_only_after(n_positional: int):
"""Allow old positional calls for one release, with a DeprecationWarning."""
def decorate(func):
sig = inspect.signature(func)
kw_names = [name for name, p in sig.parameters.items()
if p.kind is p.KEYWORD_ONLY]
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(args) > n_positional:
extra = args[n_positional:]
names = kw_names[:len(extra)]
warnings.warn(
f"passing {', '.join(names)} positionally to {func.__name__}() "
"is deprecated; pass them by keyword",
DeprecationWarning, stacklevel=2)
kwargs.update(zip(names, extra))
args = args[:n_positional]
return func(*args, **kwargs)
return wrapper
return decorate
@keyword_only_after(2)
def create_refund(order_id, amount, *, notify_customer=False, restock=False):
return f"{order_id}: refund {amount} notify={notify_customer} restock={restock}"
warnings.simplefilter("always")
print(create_refund("ORD-1001", 25.0, False, True)) # old call: still works, warns
print(create_refund("ORD-1001", 25.0, restock=True)) # new call: no warning

Output (stderr and stdout interleaved; the path is shortened):

migrate.py:35: DeprecationWarning: passing notify_customer, restock positionally to create_refund() is deprecated; pass them by keyword
print(create_refund("ORD-1001", 25.0, False, True)) # old call: still works, warns
ORD-1001: refund 25.0 notify=False restock=True
ORD-1001: refund 25.0 notify=False restock=True

The shim relies on the keyword-only parameters being declared in their old positional order. Remove it after the deprecation period, and run your tests with -W error::DeprecationWarning to find remaining callers.

  • Adding a bare * after *args. def f(*args, *, flag) fails with SyntaxError: * argument may appear only once; parameters after *args are already keyword-only.
  • Forgetting that *args captures what you meant as a flag. With def notify(order_id, *channels, urgent=False), the call notify("ORD-9", "email", True) puts True into channels and leaves urgent false.
  • Mixing keyword-only options with **kwargs. A misspelled option such as stauts="shipped" lands silently in **kwargs instead of raising TypeError. Validate the extra keys, or drop **kwargs.
  • Making everything keyword-only. get_order(*, order_id) forces get_order(order_id="ORD-1") for an argument whose meaning is already obvious. Keep the primary subject positional.
  • Changing a public signature without a deprecation period. Moving a parameter behind * is a breaking change for positional callers; warn first.
Parameter Good kind Why
The main subject (order_id, path, iterable) Positional (or positional-only) Obvious from the function name
Boolean flags (restock, dry_run) Keyword-only A bare True is unreadable
Tuning options (timeout, page_size, retries) Keyword-only Order is arbitrary; more will be added
Mandatory values that are easy to confuse (carrier, currency) Required keyword-only Forces the caller to say which is which
Two or three values with natural order (x, y) Positional Names add noise

Keyword-only parameters, the bare * and __kwdefaults__ exist in every Python 3 release (PEP 3102, Python 3.0). Related additions: dataclass kw_only and KW_ONLY in 3.10, keyword-name suggestions in TypeError messages in 3.13. Positional-only parameters, which pair with keyword-only ones in the same signature, arrived in 3.8.

1. What is the difference between def f(a, *, b) and def f(a, *args, b)? In both, b is keyword-only. The first rejects extra positional arguments with TypeError; the second collects them into args. Use the bare * when you do not want varargs.

2. Can a keyword-only parameter be required, and can it come after one with a default? Yes to both. A keyword-only parameter without a default is required, and keyword-only parameters are not subject to the “non-default after default” ordering rule.

3. Where are keyword-only defaults stored, and why does that matter? In func.__kwdefaults__, a dict, not in the __defaults__ tuple. Tools that patch or copy defaults must handle both; inspect.signature() gives a unified view.

4. Senior scenario: OrdersPortal’s internal SDK exposes charge(order_id, amount, currency, capture, idempotency_key) and production has seen double charges caused by swapped arguments. How do you fix the API? Keep order_id and amount positional, make currency, capture and idempotency_key keyword-only, and make idempotency_key required so it can never be forgotten. Release the change behind a deprecation shim that warns on positional use, track the warning count in logs, and turn warnings into errors in CI. Add a type annotation for currency (an Enum or Literal) so type checkers catch invalid values, and remove the shim in the next major version.

  • Parameters after * or *args can only be passed by name (PEP 3102, Python 3.0).
  • Use keyword-only parameters for flags, options and easily confused mandatory values.
  • They can be required, can appear in any default order and are visible through inspect.signature().
  • Dataclasses support the same rule with kw_only=True and KW_ONLY (Python 3.10+).
  • Converting a public positional parameter to keyword-only needs a deprecation period.