Sub topic 14
Choosing good signatures for your own functions
This chapter assumes you can define and call functions, and that you know how defaults, keyword arguments, *, /, *args, and **kwargs behave. It also assumes you know why items=[] is a bug. The earlier chapters explained how Python binds arguments. This chapter is about the choices you make when you write a function that other people will call.
A signature is a contract
The line def name(...) is the part of your function that callers depend on most. The body can change freely. The signature cannot, because every call site encodes assumptions about it: parameter names, their order, which ones are optional, and which are positional.
A good signature has three properties:
- Readable calls. A reader can tell what a call does without opening the definition.
- Hard to misuse. Wrong calls fail with a
TypeErrorinstead of silently doing something else. - Easy to extend. You can add options later without breaking existing callers.
Make calls readable
Consider a function with several optional settings:
def fetch(url, timeout, retries, verify, stream):
return {"url": url, "timeout": timeout, "retries": retries,
"verify": verify, "stream": stream}
print(fetch("https://example.com", 5, 3, True, False))Nobody can tell from the call what True and False mean. Reordering two parameters in the definition would also silently break every caller that passes a bool where another bool used to be.
Here is the same function with defaults and keyword-only options:
def fetch(url, *, timeout=5.0, retries=3, verify=True, stream=False):
return {"url": url, "timeout": timeout, "retries": retries,
"verify": verify, "stream": stream}
print(fetch("https://example.com"))
print(fetch("https://example.com", timeout=1.5, stream=True))Now the call documents itself. The one required value, url, is positional, and everything that tunes behavior must be named.
Choose the kind of each parameter
Use this table as a starting point for each parameter.
| Parameter is... | Make it | Why |
|---|---|---|
| The obvious main input, with an obvious order such as `min(a, b)` | Positional-or-keyword | Short calls read naturally |
| A flag, a mode, or a tuning option | Keyword-only (after `*`) | Call sites must say what the value means |
| A name that carries no meaning, or might be renamed | Positional-only (before `/`) | The name stays out of your public contract |
| An open-ended group of the same kind of thing, such as `print(*values)` | `*args` | Callers pass any count |
| Options forwarded to another function | `**kwargs` | You do not have to repeat the other function's signature |
Two rules cover most cases. Put at most two or three parameters before the *. Make every boolean parameter keyword-only.
Choose defaults carefully
A default is a promise that the common case needs no configuration. Some guidelines:
- Pick the value most callers would choose. A default of
retries=0that every caller overrides is a poor default. - Use immutable defaults. Numbers, strings,
None,True,False, and tuples are safe because they are evaluated once, at definition time, and cannot be changed. - Use
Noneas a sentinel for anything mutable or computed per call. A new list, a timestamp, or a value that depends on another parameter must be built inside the body.
def tag_all(names, *, extra=None):
extra = [] if extra is None else list(extra)
return [f"#{n}" for n in names + extra]
print(tag_all(["a", "b"]))
print(tag_all(["a"], extra=["z"]))Test with is None, not with or. The expression timeout or 30 replaces a legitimate 0 with 30, because 0 is falsy.
def wait(timeout=None):
timeout = 30 if timeout is None else timeout
return timeout
print(wait()) # 30
print(wait(0)) # 0, not 30When None is a valid answer
Sometimes None is a value the caller may want to pass on purpose. Then None cannot also mean "not provided". Create a private sentinel object, which no caller can produce by accident:
_MISSING = object()
def get_setting(config, key, default=_MISSING):
if key in config:
return config[key]
if default is _MISSING:
raise KeyError(key)
return default
settings = {"debug": False}
print(get_setting(settings, "debug")) # False
print(get_setting(settings, "port", None)) # None
print(get_setting(settings, "port", 8080)) # 8080
try:
get_setting(settings, "port")
except KeyError as e:
print("missing:", e) # missing: 'port'The built-in dict.pop works the same way. Without a default it raises, and with None as the default it returns None.
Use positional-only for names that should not matter
The / marker tells callers they cannot use the parameter's name. This is useful in two cases.
First, you want the freedom to rename the parameter later. Second, you forward **kwargs and do not want your own parameter names to collide with keys in it:
def call(func, /, *args, **kwargs):
return func(*args, **kwargs)
print(call(dict, func=1)) # {'func': 1}Without the /, call(dict, func=1) would fail with TypeError: got multiple values for argument 'func'. Because func is positional-only, the keyword func=1 goes into kwargs instead.
Do not use / everywhere. A positional-only parameter cannot be named at the call site, so it hurts readability when the value is not self-evident.
Use *args and **kwargs sparingly
A signature of (*args, **kwargs) accepts anything, so it tells the reader nothing and catches no mistakes. Callers cannot learn what is valid from help() or an editor tooltip. Reserve it for these cases:
- Real variadic functions, where the arguments are all the same kind of thing.
- Wrappers and decorators, which pass everything through unchanged.
- Subclass hooks, which pass arguments up to a parent class.
For a wrapper, use functools.wraps so the wrapped function keeps its name and signature information:
import functools
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__, args, kwargs)
return func(*args, **kwargs)
return wrapper
@logged
def area(width, height=1):
return width * height
print(area(3, height=4))With functools.wraps, inspect.signature(area) follows the __wrapped__ attribute and reports (width, height=1) instead of (*args, **kwargs).
If your function accepts **kwargs and only reads a few known keys from it, list those keys as explicit keyword-only parameters instead. A misspelled option then fails loudly instead of being ignored.
Plan for change
Callers outlive your first version. A change to a signature is safe or unsafe depending on what it does to existing calls.
| Change | Breaks existing callers? |
|---|---|
| Add a new parameter with a default | No |
| Add a new keyword-only parameter with a default | No |
| Add a new required parameter | Yes |
| Rename a positional-or-keyword parameter | Yes, for callers that used the name |
| Reorder positional parameters | Yes |
| Remove `*` so a keyword-only parameter becomes positional | No, but it commits you to an order |
| Add `*` before a parameter that was positional | Yes, for callers that passed it by position |
The safest pattern is to start with a small required core and add options as keyword-only parameters with defaults:
import csv
import sys
def export(rows, out, *, delimiter=",", header=True):
writer = csv.writer(out, delimiter=delimiter, lineterminator="\n")
if header and rows:
writer.writerow(rows[0].keys())
for row in rows:
writer.writerow(row.values())
people = [{"name": "Ada", "age": 36}, {"name": "Alan", "age": 41}]
export(people, sys.stdout)
export(people, sys.stdout, delimiter=";", header=False)If version 1 was export(rows, out), then delimiter and header were added later without touching any old call. Because they are keyword-only, you can also add more options in any order.
A decision path
The diagram summarizes how to place each new parameter.
Common mistakes
- Boolean positional flags.
render(page, True, False)is unreadable. Make the flags keyword-only. - Defaults that depend on other parameters. You cannot write
def f(a, b=a), becauseadoes not exist when thedefruns. Useb=Noneand setb = ainside the body. orfor defaulting. It overwrites0,"", and[]that the caller passed on purpose.- Mutating a list or dict argument. A caller who passes a list does not expect your function to change it. Copy it first, as
tag_alldoes withlist(extra). - Required parameters after optional ones. Python rejects
def f(a=1, b)with aSyntaxError. Put required parameters first, or use*so that later required parameters can be keyword-only. - Too many parameters. Past five or six, consider grouping related values into a dataclass or a dict that the caller builds.
Check your signature before you ship it
Print the signature, as in the introspection section earlier, and read it as a stranger would:
import inspect
print(inspect.signature(fetch))
print(inspect.signature(export))Ask whether every call you expect to see is short and clear, and whether a wrong call would fail with a TypeError.
Exercise
A function resize(image, width, height, keep_ratio, smooth) is called as resize(img, 800, 600, True, False). Rewrite the signature so that the two booleans must be named and keep_ratio defaults to True and smooth to False. Then write the call that sets only smooth=True.
Show answer
def resize(image, width, height, *, keep_ratio=True, smooth=False):. The call is resize(img, 800, 600, smooth=True). The * makes both flags keyword-only, so resize(img, 800, 600, True, False) now raises a TypeError.
Exercise
A function schedule(task, delay=None) runs delay = delay or 60. A caller passes delay=0 to run immediately but the task waits 60 seconds. Explain the cause and give the corrected line.
Show answer
The value 0 is falsy, so delay or 60 replaces it with 60. The corrected line is delay = 60 if delay is None else delay, which replaces only a missing value.
Exercise
Why is def call(func, /, *args, **kwargs) safer than def call(func, *args, **kwargs) for a function that forwards to func?
Show answer
With /, the name func is positional-only, so a caller can pass a keyword argument named func and it ends up in kwargs to be forwarded. Without /, such a call would raise TypeError: got multiple values for argument 'func'.