Sub topic 3
Keyword-Only and Positional-Only Parameters
Assume you know how to define functions, use default values, and work with tuples and dictionaries. Python lets you control how callers provide arguments. This makes function interfaces clearer and prevents accidental misuse.
Keyword-only and positional-only parameters
A slash (/) marks parameters before it as positional-only. A bare star (*) makes parameters after it keyword-only.
def create_user(user_id, /, name, *, active=True):
return {"id": user_id, "name": name, "active": active}
print(create_user(7, "Ada"))
print(create_user(7, name="Ada", active=False))
# create_user(user_id=7, name="Ada") # TypeError
# create_user(7, "Ada", False) # TypeErroruser_id must be supplied by position. active must be supplied by name. This design documents which arguments are part of the function’s stable interface.
Merging lists and dictionaries with unpacking
At a call site, * expands an iterable into positional arguments. ** expands a dictionary into keyword arguments.
The same syntax works in literals:
base = [1, 2]
all_values = [*base, 3, 4]
print(all_values) # [1, 2, 3, 4]
defaults = {"color": "red", "size": 1}
custom = {"size": 3}
settings = {**defaults, **custom}
print(settings) # {'color': 'red', 'size': 3}When dictionary keys repeat, the later value wins.
Common pitfalls and errors
A parameter cannot receive two values in one call.
def greet(name):
return f"Hello, {name}"
data = {"name": "Bob"}
try:
greet("Ada", **data)
except TypeError as error:
print(error)This raises TypeError because name was passed both positionally and by keyword. Also remember that *args is a tuple and **kwargs is a dictionary. A function expecting **kwargs receives only named arguments.
> Callout note > Use keyword-only parameters for options whose meaning is easier to understand by name, such as timeout=5 or verbose=True.
Type hints for flexible arguments
Type hints describe the collected values, not the asterisk itself.
def average(*numbers: float) -> float:
return sum(numbers) / len(numbers)
def labels(**values: str) -> dict[str, str]:
return values
print(average(2.0, 4.0))
print(labels(first="Ada"))Here, numbers is a tuple of floats, and values is a dictionary whose keys are strings and whose values are strings.
Exercise
In def configure(name, *, debug=False):, how must the caller provide debug?
Show answer
The caller must provide it by keyword, such as configure("app", debug=True).