Skip to content

Module 9 · Functions — topic 7 of 19

Keyword arguments

Passing arguments by parameter name for clarity and flexibility, mixing them with positional arguments, and forcing callers to use names with keyword-only parameters.

Beginner 8 min read·Lesson 132 of 306 in Python Programming

Learning objectives

  • Call functions using keyword arguments
  • Combine positional and keyword arguments legally
  • Define keyword-only parameters with *

Definition

A keyword argument is written as name=value in a call and is assigned to the parameter with that name, regardless of position.

Introduction

print("a", "b", sep="-") uses a keyword argument: sep is named, so its meaning is clear at the call site and its position doesn't matter.

Why it matters

Keyword arguments make calls self-documenting — send(to=..., subject=..., urgent=True) is far clearer than send(x, y, True) — and they let functions grow new optional parameters without breaking old calls.

Detailed explanation

Keyword arguments can appear in any order, but must come after all positional arguments.

Each keyword must match a parameter name exactly (or be accepted by **kwargs).

Boolean flags should almost always be passed by keyword: archive(report, compress=True) instead of archive(report, True).

A bare * in the parameter list makes every following parameter keyword-only: def connect(host, *, timeout=10, retries=3) forces callers to write timeout=... explicitly.

Keyword arguments also protect code as it evolves. If a library later inserts a new parameter in the middle of a signature, positional calls silently shift every value into the wrong slot, while keyword calls keep working. That is why many modern APIs make most of their options keyword-only from the start, and why style guides recommend naming any argument whose meaning isn't obvious from the value itself.

Syntax

Python
def connect(host, *, timeout=10, retries=3):
...
connect("db.local", retries=5) # OK
connect("db.local", 5) # TypeError: timeout is keyword-only
  • name=value assigns by name.
  • Keywords after positionals.
  • Parameters after * are keyword-only.

Code examples

Keywords in any order

Python
def ticket(name, seat, meal):
return f"{name} | seat {seat} | {meal}"
print(ticket(meal="veg", name="Asha", seat="12A"))
print("a", "b", "c", sep=" -> ", end=" !\n")
Output
Asha | seat 12A | veg
a -> b -> c !

Keyword-only parameters

Python
def connect(host, *, timeout=10, retries=3):
return f"{host} timeout={timeout} retries={retries}"
print(connect("db.local", retries=5))
try:
connect("db.local", 5)
except TypeError as e:
print(e)
Output
db.local timeout=10 retries=5
connect() takes 1 positional argument but 2 were given

More examples

Readable calls with flags

Python
def export_report(rows, *, as_csv=False, include_header=True, delimiter=","):
lines = []
if include_header:
lines.append(delimiter.join(["name", "marks"]))
for name, marks in rows:
lines.append(delimiter.join([name, str(marks)]) if as_csv else f"{name:<6}{marks:>4}")
return "\n".join(lines)
data = [("Asha", 91), ("Ravi", 74)]
print(export_report(data, as_csv=True))
print(export_report(data, include_header=False))
Output
name,marks
Asha,91
Ravi,74
Asha    91
Ravi    74

Step-by-step explanation

  • The * makes as_csv, include_header and delimiter keyword-only.
  • The first call asks for CSV with the default header.
  • The second call keeps the table format and turns the header off.
  • Because the flags must be named, each call is readable without looking up the definition.

Expected output

Running “Readable calls with flags” prints exactly:

TextOutput
name,marks
Asha,91
Ravi,74
Asha 91
Ravi 74

Practical applications

  • Library functions like open(path, mode=..., encoding=...) and sorted(..., key=..., reverse=...) are used with keywords.
  • Configuration-heavy functions use keyword-only parameters to stay readable.

Best practices

  • Pass booleans and optional settings by keyword.
  • Make optional configuration parameters keyword-only with *.
  • Match keyword names exactly to the documentation.

Common mistakes

Misspelled keyword

Avoid

sorted(names, reversed=True)

Prefer

sorted(names, reverse=True)

An unknown keyword raises TypeError: unexpected keyword argument.

Positional after keyword

Avoid

ticket(name="Asha", "12A", "veg")

Prefer

ticket("Asha", seat="12A", meal="veg")

Positional arguments can't follow keyword arguments: SyntaxError.

Important notes

  • Keyword-only parameters were introduced in Python 3.

Key takeaways

  • name=value matches by name, in any order.
  • Keyword arguments must follow positional ones.
  • Parameters after a bare * must be passed by keyword.

Try it yourself

  1. 1
    Write make_username(first, last, *, lower=True, sep=".") and call it three different ways.
  2. 2
    Rewrite a call like save(data, True, False) using keyword arguments so it is self-explanatory.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic