Lesson · Functions
Designing Function APIs & Sentinel Values
72 min readDesigning Function APIs & Sentinel Values
A good function API makes valid calls easy and invalid calls obvious. Sentinel objects solve cases where `None` is a valid value and you must distinguish 'omitted' from 'explicitly supplied'.
Learning goals
- Explain what a function contract contains: responsibilities, accepted inputs, return meaning, side effects, and raised errors.
- Read a signature and say which parameters are required, which have defaults, and which are keyword-only, and why.
- Predict when
Noneis ambiguous and design a unique sentinel such asMISSING = object()instead. - Choose between raising
KeyErrorand returning a default for a missing key, and defend the choice. - Add an optional keyword-only parameter to an existing function without breaking current calls.
Mental model
A sentinel works because it is a unique object: default is MISSING is true only when the caller omitted the argument, so every possible user value, including None, keeps its meaning. This is the last piece of API design after responsibilities, parameters, and return values: state the contract, make valid calls easy, and let invalid calls fail loudly. The fence shows the decision order the body must implement to keep those promises.
The sentinel keeps omission distinct from data
MISSING = object(), compared with is
Mental model
the same mechanism as a compact list
contract: get_setting(mapping, key, default=MISSING) ↓ caller omits default default is MISSING (checked with is) ↓ key present? return the stored value, even if it is None ↓ key missing, nothing said → raise KeyError, the failure is explicit ↓ key missing, real default → return that default instead
Core idea
Good API design is contract design: a function should have one coherent responsibility, parameters that expose only what callers control, and a return meaning stable enough to reason about from the call site. The sentinel pattern (MISSING = object() plus an is check) exists for the corner where None is legitimate data, because "argument omitted" still needs its own unique signal; and when the contract is violated, raising beats silently substituting a value.
Clear function responsibilities
A function is easiest to understand when it has one coherent purpose and a small, explicit contract. Split unrelated side effects or policy decisions into collaborators when they obscure that purpose.
Parameter design
Parameters should expose the information callers truly control while hiding internal implementation details. Use names, defaults, and positional/keyword restrictions to make correct calls obvious.
Return-value design
A return value should have a stable meaning that callers can reason about. Avoid mixing unrelated result shapes or using special values when a clear exception or result type would better express failure.
Pure functions vs side effects
An editor should make the active interpreter visible and provide syntax, linting, debugging, and terminal access without hiding how Python itself runs. Keep environment selection explicit.
Keyword-only APIs
Keyword-only options make call sites self-documenting and allow new optional parameters to be added without changing positional meaning. They are especially useful for Boolean or numeric tuning parameters.
Avoiding ambiguous Boolean flags
A call such as render(data, True, False) hides meaning. Prefer keyword-only flags, enums, or separate functions when Boolean combinations represent distinct modes.
Validation boundaries
Validation boundaries should happen at a boundary where invalid data can be rejected with a useful error. Keep validation rules explicit and avoid silently converting values in ways that hide mistakes.
None as a meaningful value
None often represents absence, but some APIs legitimately accept None as data. In those APIs, a unique sentinel is needed to represent 'argument omitted'.
Sentinel objects when None is not enough
Create a unique sentinel such as MISSING = object() and compare with is. This keeps omission distinct from every possible user-supplied value.
Function contracts
A function contract includes accepted inputs, return semantics, side effects, errors, and relevant performance assumptions. Tests and documentation should reinforce the same contract.
Backward-compatible API evolution
Evolve public functions by preserving existing call meaning where practical. Keyword-only additions, deprecation periods, and adapter layers can reduce breakage for callers.
Walkthrough
MISSING = object()creates one unique object; nothing else in the program can ever be identical to it, which is what makes it usable as an omission marker.def get_setting(mapping, key, default=MISSING)makesdefaultoptional: calls that omit it leave the parameter bound to the sentinel, while calls that pass any value, includingNone, replace it.print(get_setting(settings, "theme"))finds"theme"present with the valueNoneand returns thatNone, proving the sentinel kept "explicitly supplied" distinct from "omitted".- Predict before running: the second call passes
"en"for the missing key"language"; decide what it returns and whatget_setting(settings, "language")would do instead.
Experiments to try
- Call
get_setting(settings, "language")and read theKeyError; then call it withdefault=Noneand explain whyNoneis now an ordinary default rather than the omission marker. - Create
sentinel = object()next toMISSINGand checksentinel is MISSINGandsentinel == MISSING; both areFalse, which is exactly why the code compares withis. - Pass the sentinel explicitly with
get_setting(settings, "language", MISSING); the call still raisesKeyError, and you can explain why callers should never treat the sentinel as ordinary data. - Replace
default=MISSINGwithdefault=Noneand try to express both remaining behaviors; find the case that becomes impossible to distinguish.
Playable lesson
Lab: Sentinel vs None
Compare an omitted argument with an explicit None and other falsey values. Show identity checks against a unique sentinel.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Sentinel vs None
MISSING is a unique object, compared with isget_setting(settings, "theme")
returns None
The key exists, so the stored value wins outright. That value can be None or 0 and still be returned, because presence is decided by the key.
Predict first
Missing key. Does an omitted default and `default=None` behave the same?
Predict first
Why compare with `default is MISSING` rather than `default == MISSING`?
Predict first
`settings = {"theme": None}`. What does `get_setting(settings, "theme")` return?
The trap: reading None as a missing key. With an omitted default it raises; with None passed it returns None.
Common mistakes
- Using
Noneas the omission marker in an API whereNoneis valid data: an explicitly suppliedNonebecomes indistinguishable from an omitted argument, and one of the two behaviors is silently lost. - Comparing a sentinel with
==instead ofis: equality can be customized and can accidentally succeed, while identity can only match the one sentinel object itself. - Letting a function do several unrelated jobs (validation, lookup, printing, caching) so no single contract describes it; callers then cannot tell which failures to expect or which side effects to tolerate.
- Growing a public signature by inserting a positional parameter: existing positional call sites shift meaning, so prefer keyword-only additions that preserve every current call.
Practice: Easy
- Run the worked example unchanged and write down both printed lines; next to each, name the branch of
get_settingthat produced it. - Call
get_setting(settings, "language")and record the exactKeyError; then callget_setting(settings, "language", "en")and explain which parameter made the difference. - Replace
MISSING = object()withMISSING = Noneand run the example again; describe the two behaviors that now conflict and pick which one breaks.
Practice: Medium
- Add a keyword-only
verbose=Falseparameter toget_settingthat prints which branch was taken, and check that every call from the worked example still behaves identically. - Write
def divide(a, b, *, on_zero=MISSING): returna / bnormally, letZeroDivisionErrorpropagate when no policy was given, and returnon_zero(possiblyNone) otherwise; document the contract in a docstring. - Take one of your functions with an ambiguous Boolean call such as
render(data, True, False)and redesign it with keyword-only flags; list which call sites keep working unchanged and which need edits.
Practice: Hard
- Design the full contract for
get_settingv2: support dotted keys such as"ui.theme", document the failure policy for each lookup step, add at least one keyword-only option, and keep the sentinel for every optional parameter; write the docstring before the code, then implement it. - Build a sentinel test lab: create two candidates with
object()and a third from a class whose__eq__always returnsTrue; show withisand==checks which candidate is safe as an omission marker and which can betray you, and explain each result. - Evolve
def render(data, scale, colour)in two ways: insert a new positional parameter afterdata, then add the same parameter as keyword-only. Run one old call against each version, compare the errors, and state why the keyword-only addition preserves every existing call.
Lesson checklist
- I can describe a function contract in one sentence: inputs, return meaning, side effects, and errors.
- I can explain why a unique sentinel checked with
isdistinguishes omission from any user value, includingNone. - I can choose keyword-only parameters to make call sites self-documenting.
- I can extend a public signature without changing the meaning of existing calls.
Remember
An API is a contract: one coherent responsibility, parameters that expose only what callers control, returns with a stable meaning, and errors that stay explicit. The sentinel pattern protects the one corner where `None` is real data, since `MISSING = object()` compared with `is` is the only way to keep "omitted" distinct from every value a caller may supply.
Interview angles
What is the main purpose of **Clear function responsibilities**?+
A function is easiest to understand when it has one coherent purpose and a small, explicit contract. Split unrelated side effects or policy decisions into collaborators when they obscure that purpose.
What should you pay attention to when using **Parameter design**?+
Parameters should expose the information callers truly control while hiding internal implementation details. Use names, defaults, and positional/keyword restrictions to make correct calls obvious.
How does **Return-value design** fit into this lesson?+
A return value should have a stable meaning that callers can reason about. Avoid mixing unrelated result shapes or using special values when a clear exception or result type would better express failure.
What goes wrong when `None` is used as the omission marker in an API that accepts `None` as data?+
The two cases collapse into one: an explicitly supplied None and an omitted argument look identical inside the function, so it can no longer raise for one without also raising for the other. A unique MISSING = object() compared with is keeps the two cases distinct.