Topic 56 of 64
Keyword Arguments
Overview
Keyword arguments are passed by name rather than position, making function calls self-documenting and order-independent. They are heavily used in APIs, configuration functions, and any function with many parameters.
Syntax
python
def create_user(name: str, age: int, role: str = "user"):
return {"name": name, "age": age, "role": role}
# Keyword arguments — order doesn't matter
create_user(age=25, name="Alice", role="admin")
# Mix positional and keyword (positional must come first)
create_user("Alice", age=25)
# Keyword-only parameters (after * in signature)
def connect(host: str, *, port: int, timeout: float = 30.0):
pass
connect("localhost", port=5432) # OK
connect("localhost", 5432) # TypeError!Common Pitfalls
- Keyword-only arguments (after *) must always be passed by name — great for preventing API breakage when adding parameters.
- You cannot pass a keyword argument twice — create_user('Alice', name='Bob') raises TypeError.
- Interview tip: Using ** to unpack a dict as keyword arguments: func(**{'a': 1, 'b': 2}) is equivalent to func(a=1, b=2).
Real-World Example
Self-documenting function call for configuring a report
example
python
def generate_report(
data: list,
*,
format: str = "pdf",
include_charts: bool = True,
page_size: str = "A4",
author: str = "System",
) -> dict:
return {
"format": format, "records": len(data),
"charts": include_charts, "size": page_size,
"author": author,
}
# Very readable call:
report = generate_report(
sales_data,
format="excel",
include_charts=False,
author="Finance Team",
)