Sub topic 14
Choosing good signatures for your own functions
This chapter assumes you know how defaults are evaluated once at definition time, how the None sentinel avoids shared mutable defaults, and what *, /, *args and **kwargs do in a definition. Here you combine those tools to design signatures that are hard to misuse.
Start from the call site
A signature is the public interface of a function. Write the call you want people to type first, then shape the signature to fit it. A call like connect("db.local", 5432, 5, True) forces the reader to guess what 5 and True mean. A call like connect("db.local", timeout=5, ssl=True) documents itself.
Guidelines
- Put required parameters first and keep them few. The values every caller must supply belong at the start, in the order a reader would expect.
- Give optional behavior a default. Pick the default that is right for most callers, so the common call stays short.
- Use
Noneas the sentinel for mutable or computed defaults. Never put a list, dict or set in the signature. Create it inside the function. - Make flags and tuning options keyword-only with
*. Booleans and numbers that are easy to confuse should be named at every call. - Use
/only when the name should not be part of the API. The parameter name of a positional-only parameter can be renamed later without breaking callers. - Accept
*argswhen the function takes any number of similar values. Accept**kwargsmainly to forward options to another function, not to hide the real parameters.
Why keyword-only helps you change code later
If timeout is keyword-only, you can add a new parameter before it or reorder the others, and no existing call breaks. If it is positional, any caller that passed it by position now depends on its location.
def fetch(url, *, timeout=10, retries=3, verify=True):
return (url, timeout, retries, verify)
print(fetch("https://example.com", retries=0))
# ('https://example.com', 10, 0, True)Using None when None is a valid value
The None sentinel fails if callers may legitimately pass None. In that case, make a private sentinel object so you can tell "not given" from "given as None".
_MISSING = object()
def get_setting(settings, key, default=_MISSING):
if key in settings:
return settings[key]
if default is _MISSING:
raise KeyError(key)
return default
config = {"debug": False}
print(get_setting(config, "debug")) # False
print(get_setting(config, "port", None)) # None
print(get_setting(config, "port", 8080)) # 8080Forwarding arguments
*args and **kwargs let a wrapper pass everything through without repeating the signature. The wrapper then accepts whatever the target accepts.
def log_call(func, *args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
def area(width, height=1):
return width * height
print(log_call(area, 4, height=3)) # prints "calling area", then 12The cost is that the wrapper's own signature no longer shows the real parameters. Prefer explicit parameters when the function is part of your main API.
Quick review checklist
| Question | Good answer |
|---|---|
| Can a call be read without opening the definition? | Options are passed by keyword |
| Does any default hold a list, dict or set? | No, use `None` and create it inside |
| Could a new option break old calls? | No, new options are keyword-only |
| Is `**kwargs` hiding real parameters? | No, it only forwards to another call |
Exercise
Rewrite this signature so it is safer and clearer to call: def send(message, recipients=[], retry=True, delay=5). Explain each change.
Show answer
def send(message, recipients=None, , retry=True, delay=5):
if recipients is None:
recipients = []
...
The list default is replaced with None, and the list is created inside the function, so calls do not share one list. The ` makes retry and delay keyword-only, so callers write send("hi", retry=False) instead of an unclear send("hi", [], False, 5)`, and new options can be added later without breaking existing calls.
Exercise
A function lookup(table, key, default=None) must tell apart "no default given, raise an error" from "default is None". How do you do it?
Show answer
Use a private sentinel such as _MISSING = object() as the default value. Inside the function, test default is _MISSING to raise an error. Any other value, including None, is returned as the caller's chosen default.