Follow functions and error boundaries
You can inspect an edit now and run it in a known environment, thanks to the last root lesson. Here I want to make the behaviour behind those lines easier to judge: what does each function promise, and which failures can it handle honestly?
We will expand the small function from the start of the chapter. You will learn to:
- Trace local names and shared mutable values.
- Follow a function across an import boundary.
- Handle an expected exception while keeping unexpected faults visible.
Together, these let you follow an input without losing track of who changes it or handles its failure.
Give a function one responsibility you can check
Suppose a book lookup receives a chapter number as text. It needs a positive whole number before it can search. That is a separate responsibility from finding a chapter or displaying an answer:
def parse_chapter_number(text):
number = int(text)
if number < 1:
raise ValueError("Chapter number must be positive")
return number
int(text) attempts the conversion. raise reports a failure instead of returning a normal result. ValueError is an exception type for a value that is unsuitable for this operation.
For "2", the function returns 2. For "two", conversion raises ValueError. For "0", our own check raises ValueError with the more specific message. These are different causes that share the same broad outcome: no valid chapter number was produced.
Notice the contract, the expected inputs, results and failures, that you can state without writing Python: “Given text representing a positive whole number, return that number. Otherwise report invalid input.” That statement is what your checks should test. A function name alone does not establish the contract.
Keep local names inside the call
The name number above is local to that function call. Its scope is the part of the program where the name is available. Another function can use its own local name number without changing this one.
number = 7
def next_number(number):
return number + 1
result = next_number(2)
print(number)
print(result)
This prints 7 and then 3. The argument 2 becomes the function's local number; the name outside still refers to 7.
If a function relies on names defined outside it, include those dependencies in your reading. An apparently simple function may depend on a changing setting or shared dictionary. Passing a needed value as a parameter often makes the responsibility easier to inspect and test.
Remember the shared-list example from Lesson 3, though. Passing a list into a function does not copy it. A local parameter name can still refer to the caller's mutable object. Local scope prevents a name from leaking; it does not automatically prevent changes to shared data.
Read the call as carefully as the definition
Python lets a caller supply values by position or by parameter name. Defaults fill omitted parameters, but a default is chosen when the function is defined. A mutable default can therefore survive across calls:
def record_title(title, titles=[]):
titles.append(title)
return titles
The same default list is reused. A second call can contain the first call's title even if the caller expected a fresh list.
A common repair makes the fresh-list decision inside each call:
def record_title(title, titles=None):
if titles is None:
titles = []
titles.append(title)
return titles
This avoids sharing the default list. It still modifies a list explicitly supplied by a caller. If the requirement forbids that, copy the supplied list too. Read the requirement before calling the repair complete.
Use a module without hiding its behaviour
A module is a unit of Python code you can import, commonly a .py file. Put parse_chapter_number into chapter_numbers.py. A second file can use it:
from chapter_numbers import parse_chapter_number
print(parse_chapter_number("2"))
from ... import ... makes the named function available in the importing file. Another form, import chapter_numbers, keeps the module name visible at the call: chapter_numbers.parse_chapter_number("2").
A package groups importable modules. You will often see __init__.py in a package folder. The name used to install a library may differ from its name in an import statement. Check the library's documented import rather than assuming the names match.
An import can also sit inside a function. In that position, it executes when the call reaches that line. This can defer an optional dependency until it is needed; it can also defer a missing-library error. When tracing a failure, check where the import executes rather than assuming every import happened at startup.
Your working folder already has a small layout with separate responsibilities:
| File or folder | Responsibility |
|---|---|
| chapter_numbers.py | The importable parsing function |
| chapter_labels.py | The earlier script that defines and calls a label function |
pyproject.toml and uv.lock | The dependency choices and their resolved versions |
.venv | The environment's installed interpreter and libraries |
Keep your own source files outside the environment folder. A larger solution may group modules into a package, but the same distinction holds: find the source, the dependency declarations and the installed environment separately.
Importing a module can execute its top-level instructions. A file with an unguarded print or network request may do that work when imported. To separate a direct run from an import, Python provides a name check:
if __name__ == "__main__":
print(parse_chapter_number("2"))
When Python runs that file directly, its __name__ is "__main__" and the block runs. When another file imports it, the block does not run. Function definitions outside the block remain available to import. This prevents a demonstration from running unexpectedly when a test imports its function.
Catch an expected failure at the place that can respond
The number parser should report bad input. The part speaking to a reader can choose a helpful response:
def number_reply(text):
try:
number = parse_chapter_number(text)
except ValueError:
return "Please give a positive whole chapter number."
return f"Looking for chapter {number}."
try marks the operation whose failure we expect. except ValueError handles that specific kind of failure. An unrelated programming error should remain visible so it can be investigated.
This alternative hides too much:
try:
result = parse_chapter_number("two")
except Exception:
result = 1
It turns invalid input into a plausible chapter number without permission. It can also hide other exceptions that need attention. The absence of a traceback does not mean the answer is correct.
finally runs when leaving a try statement, including when an exception occurs. It is useful for cleanup. Avoid putting a return there casually: it can replace an earlier result or suppress an exception. For files, the next Python lesson will show the clearer with form.
Explain the boundary before changing it
The Python function guide, module tutorial and exception tutorial support the behaviours used here.
Try these without the explanation in view:
- Why does
next_number(2)leave the outside namenumberunchanged? - Why can a function still modify the caller's list through a local parameter?
- What survives across calls in the first
record_titleversion? - Which failure should
number_replyconvert into a reader-facing message? Which failures should remain visible? - What would happen if an imported file started a server at its top level?
Check after your attempt
The call has its own parameter binding. A binding can still refer to the same mutable list as the caller. The default list was created once, at function definition. The expected ValueError can become an input message; unexpected faults need investigation. Top-level server startup can occur during import, which is why deliberate startup belongs under the main-name guard.
Ask the AI to propose tests for valid text, invalid text and a non-positive number. Check the expected behaviour yourself before accepting its tests. In the next root lesson, these inputs travel across an HTTP and JSON boundary, where “text” and “a Python value” become a particularly useful distinction.