Python Keyword-Only Parameters: Clearer Calls (3.0+)
What you’ll learn
Section titled “What you’ll learn”- How the bare
*and*argsturn 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)andKW_ONLYapply 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.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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=TrueORD-1001: refund 25.0 notify=False restock=TrueTypeError: create_refund() takes 2 positional arguments but 4 were givenThe new call is self-describing, the caller can skip notify_customer entirely, and the old ambiguous call now fails loudly.
How it works
Section titled “How it works”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 DHLTypeError: ship_order() missing 1 required keyword-only argument: 'carrier'['ORD-1:vip', 'ORD-2:vip']csv -> s3://exports.example.test/dailyorder_id POSITIONAL_OR_KEYWORD <class 'inspect._empty'>carrier KEYWORD_ONLY <class 'inspect._empty'>express KEYWORD_ONLY False{'express': False}9.50 EUR 9.50 USDRules 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 asKEYWORD_ONLY. - A bare
*needs at least one name after it.def f(a, *):is aSyntaxError: named arguments must follow bare *. - Unknown keywords fail. Without
**kwargs, a misspelled keyword raisesTypeError. 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.
Keyword-only fields in dataclasses
Section titled “Keyword-only fields in dataclasses”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__.
Realistic example
Section titled “Realistic example”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, dataclassfrom 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 givenProduction patterns
Section titled “Production patterns”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 functoolsimport inspectimport 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, warnsprint(create_refund("ORD-1001", 25.0, restock=True)) # new call: no warningOutput (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, warnsORD-1001: refund 25.0 notify=False restock=TrueORD-1001: refund 25.0 notify=False restock=TrueThe 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.
Common mistakes
Section titled “Common mistakes”- Adding a bare
*after*args.def f(*args, *, flag)fails withSyntaxError: * argument may appear only once; parameters after*argsare already keyword-only. - Forgetting that
*argscaptures what you meant as a flag. Withdef notify(order_id, *channels, urgent=False), the callnotify("ORD-9", "email", True)putsTrueintochannelsand leavesurgentfalse. - Mixing keyword-only options with
**kwargs. A misspelled option such asstauts="shipped"lands silently in**kwargsinstead of raisingTypeError. Validate the extra keys, or drop**kwargs. - Making everything keyword-only.
get_order(*, order_id)forcesget_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.
When to use it and when not to
Section titled “When to use it and when not to”| 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 |
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”- Parameters after
*or*argscan 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=TrueandKW_ONLY(Python 3.10+). - Converting a public positional parameter to keyword-only needs a deprecation period.
Related pages
Section titled “Related pages”- Positional-only parameters: the
/marker, the counterpart of*. - Splat operator:
*args,**kwargsand argument unpacking. - Functions: parameters, defaults and calling conventions.
- Function basics: a gentler introduction to arguments.
- dataclasses:
kw_onlyfields in generated constructors. - Type hints: annotating keyword-only parameters.