Functions with Clear Responsibilities
Python Function Interfaces
BOTIE
Python's argument system lets a function make dependencies explicit, including keyword-only options. Separating a calculation from its surrounding effects is a design choice built with those language features. It allows a report writer and a web page to reuse the same result without inheriting each other's printing or storage behavior.
Sources for this history
Why Does Calculating an Alert Also Print a Report?
Botie needs an alert count in a web page and in a daily text report. The existing helper calculates the count, prints a message and changes a global list. Calling it for the web page also changes the report state.
The problem is where those responsibilities live. We can calculate a result from explicit inputs, return it, and let the caller decide how to display or save it. That gives both callers the same numerical rule without forcing them to share the same side effects.
This workshop calculates a summary. It does not print a report, write a file or contact a web page.
Step 1 of 1
Separate the result from its presentation
One calculation can serve callers with different output formats.
| Stage | Input | Result or effect |
|---|---|---|
| calculate | Celsius readings and inclusive limit | count and total excess |
| format | calculated result | text for a person |
| publish | formatted message | chosen external effect |
calculate
- Input
- Celsius readings and inclusive limit
- Result or effect
- count and total excess
format
- Input
- calculated result
- Result or effect
- text for a person
publish
- Input
- formatted message
- Result or effect
- chosen external effect
Keep one coherent responsibility
Both results describe the same selected readings. Formatting a sentence or updating a web page can happen after this calculation.
Calculate an Alert Summary
Readings of 20, 25 and 30 degrees Celsius arrive with an alert limit of 25. Two readings reach that limit. Together they are 5 degrees above it: the reading of 25 contributes zero, and 30 contributes five.
BOTIE
Alert count and total excess temperature
- count
- 2
- excess_c
- 5
Follow the operations
1. Celsius readings
- 020
- 125
- 230
2. Alert limit in Celsius
25
3. Keep readings at or above the limit
- 025
- 130
4. Count items
2
5. Subtract
- 00
- 15
6. Add a list
5
7. Collect the alert summary
- count
- 2
- excess_c
- 5
8. Result
- count
- 2
- excess_c
- 5
This workshop calculates a summary. It does not print a report, write a file or contact a web page.
1. Keep one coherent responsibility
A useful function has a job that a caller can describe. Calculating an alert summary is one such job. Sending emails and changing account settings are separate responsibilities with different failure behavior.
This is not a rule about a maximum number of lines. Splitting every expression into another function can hide a simple procedure. Keep a function together when its steps belong to the same result.
Use the smallest design that keeps the current requirements understandable. KISS is a reminder to keep the solution simple, not a prohibition on necessary structure.
2. Make the dependencies explicit
Pass the limit to the function instead of reading a mutable global variable. A keyword-only argument requires the caller to name an option, which can prevent a confusing positional call.
The star in the signature below separates positional arguments from keyword-only arguments. A default is part of the function's agreement, so choose it deliberately.
A keyword states what a value means at the call site.
Name a reporting option
Use a keyword-only limit while keeping readings as the main input.
def count_alerts(readings_c, *, limit_c):
return sum(value >= limit_c for value in readings_c)
print(count_alerts([19, 23, 25], limit_c=23))2The caller can see the inclusive limit without remembering a second positional argument.
Check yourself
Questions on Parts 1 to 2
Question 1 of 2
Which boundary would support both callers?
Question data
A helper counts alerts, sends an email and edits a global list. A web page needs only the count.3. Return data before choosing its display
A pure calculation returns a result determined by its inputs without changing them or producing external effects. It can still use local variables and loops. Purity describes the observable behavior, not the absence of assignments.
Return a record when the caller needs several named results. A separate formatter can turn that record into a message. Keep rounding in the presentation unless the calculation itself requires a defined rounding rule.
Testing the calculation does not need to capture a console or undo a write.
Choose text after the calculation
The summary is usable data before it becomes a display message.
def maximum_temperature(readings_c):
if not readings_c:
raise ValueError("At least one reading is required")
return max(readings_c)
maximum_c = maximum_temperature([16, 21, 18])
print(f"Highest reading: {maximum_c:.1f} C")Highest reading: 21.0 CThe function does not choose the wording or print anything itself.
4. Keep effects at a deliberate boundary
Reading a file, sending a message and updating a shared collection are effects. A program needs effects, but a caller should know when they occur. Keep a numerical helper free of hidden writes, then call an explicit save or send operation when the result is ready.
Some functions appropriately mutate an object. Name and document that behavior. A function that promises a new report should not quietly edit the input report instead.
The workshop returns summary data. The programming challenges verify that repeated calls do not accumulate hidden state.
5. Refactor because a requirement changed
Start with the straightforward procedure. Extract a formatter when another display is needed, or a shared calculation when another caller needs the same rule. Creating a hierarchy of generic managers before those needs appear adds decisions that the problem has not asked us to make.
A useful abstraction removes a real dependency or keeps a shared decision in one place. Its value is easier to judge against an actual caller.
Check yourself
Questions on Parts 1 to 5
Question 1 of 4
Using a local mutable value automatically makes the function impure.
Question data
A function uses a local list to collect results, then returns a new list without changing its inputs.Try it with Botie
Build with Botie
Write and run Python