Follow callables and decorators
The @dataclass line in Lesson 1 supplied behaviour around a class. Soon you will see a similar-looking line register a tool. Before trusting either, it helps to understand the ordinary Python underneath.
We will follow three small changes:
- Passing a function as a value.
- Returning a function that remembers a value.
- Applying a decorator and forwarding its arguments.
You can then inspect what happens around a framework call, including changes to its arguments or returned result.
Pass the operation instead of its result
Start with a familiar text function:
def clean_title(title):
return title.strip()
operation = clean_title
print(operation(" Python and Roots "))
clean_title without brackets refers to the function itself. clean_title(...) calls it and produces a result. Here operation refers to the same function, so calling operation runs that function.
A callable is a value Python can call with parentheses. Functions are callables, but they are not the only kind. A framework may accept a callable rather than require one particular function name.
Another function can receive the operation:
def prepare_title(text, cleanup):
return cleanup(text)
result = prepare_title(" Python and Roots ", clean_title)
The second argument is the function, not an already-cleaned title. This is why adding or removing parentheses can change a framework configuration completely. Supplying clean_title() would attempt an immediate call without its required title argument.
Return a function with a remembered value
Functions can also create and return other functions:
def make_prefixer(prefix):
def add_prefix(title):
return f"{prefix}: {title}"
return add_prefix
label = make_prefixer("Chapter")
print(label("Python and Roots"))
make_prefixer runs first. Its local prefix is used by the inner function. The outer call returns that inner function, which we name label. Calling label later still uses the remembered prefix.
This is a closure, a function retaining access to names from its enclosing scope. You do not need to recreate one from memory. When reading one, identify the saved value and check whether it can change or refer to shared mutable data. A remembered dictionary can still be a shared dictionary.
Expand the decorator into an ordinary call
A decorator receives a definition and returns the value that will be bound to its name. For a function, a common result is a wrapper that adds work around the original call:
def announce(function):
def wrapped(title):
answer = function(title)
return f"Found: {answer}"
return wrapped
@announce
def clean_title(title):
return title.strip()
For the assignment of the function name, the @announce form means:
clean_title = announce(clean_title)
The decorator is applied when the definition executes. The returned wrapper runs when you later call clean_title(" Python and Roots "). That call returns Found: Python and Roots.
There are two different moments to inspect: definition time and call time. A tool-registering decorator may record the function at definition time rather than immediately perform its work. Its exact behaviour belongs to that decorator's contract. The @ symbol alone does not tell you what it does.
In this example, replace return f"Found: {answer}" with print(f"Found: {answer}"). The prefix still appears on screen, but the caller now receives None: printing does not return the string. The return-value mistake from your first lesson can reappear inside several layers of a framework.
Recognise the arguments a wrapper forwards
A general wrapper may not know every parameter in advance. You will see:
def wrapped(*args, **kwargs):
return function(*args, **kwargs)
In the definition, *args collects extra positional arguments into a tuple. **kwargs collects keyword arguments into a dictionary. The names are conventional; the stars supply the behaviour.
At the call inside the wrapper, the stars unpack those collections back into arguments. For wrapped("Python and Roots", compact=True), args contains the title and kwargs contains {"compact": True}. The wrapper then forwards both.
This short form is not enough to prove a wrapper is transparent. It may still change arguments, catch errors, log private input or replace the return value. Follow the lines around the forwarding call.
Python's functools.wraps can preserve useful function metadata such as its name and documentation when building a wrapper. Metadata matters when a framework inspects a function to describe its tool. Preserving metadata still does not prove that the wrapper preserves behaviour.
Read the decorators in a test file
You have already used pytest's built-in tmp_path fixture. A fixture supplies a test with prepared data or a resource. Now you can recognise how a test file declares one of its own. Keep the chapter-number function from Chapter 1 beside this new test file, test_chapter_numbers.py:
import pytest
from chapter_numbers import parse_chapter_number
@pytest.fixture
def chapter_number_text():
return "7"
def test_parses_prepared_text(chapter_number_text):
assert parse_chapter_number(chapter_number_text) == 7
@pytest.mark.parametrize("text, expected", [("1", 1), ("7", 7)])
def test_parses_each_number(text, expected):
assert parse_chapter_number(text) == expected
Run uv run python -m pytest -q test_chapter_numbers.py. Expect three passing cases: the fixture-based test once, then the parametrised test twice.
@pytest.fixture registers the preparation function. Pytest sees the test parameter named chapter_number_text, runs the matching fixture and supplies its returned value. Python does not do this automatically for every function parameter; pytest coordinates it.
@pytest.mark.parametrize associates two sets of arguments with the second test. Pytest runs that test once for each pair. Read the supplied inputs and expected results; a long list of cases is useful only when it challenges the requirement. The fixture guide and parametrisation guide explain these two different decorator contracts.
Inspect what the framework receives
When you meet @tool or a route decorator in an AI-written solution, ask:
- Which callable is being supplied or registered?
- Which arguments will the framework pass, and who validates them?
- What value comes back to the caller?
- What other work happens around the call?
These questions are more useful than memorising the name of every decorator. Some decorators return a normal function; others return a framework object with methods such as invoke. You must read the documented return shape before calling it as though nothing changed.
The Python glossary entry on decorators, argument guide and functools reference support this explanation.
Trace both moments without the page
- What is the difference between passing
clean_titleand passingclean_title("x")? - What happens when
announceis applied, and what happens later when its result is called? - What information sits in
argsandkwargsfor the example call above? - What would a missing
returninside the wrapper change? - Why is preserving a function's name insufficient evidence that the wrapper is safe?
Check after you have traced it
One passes a callable; the other passes a call's result. Applying announce returns a wrapper, while calling that wrapper later runs the original function and adds a prefix. The title is positional and compact=True is a keyword entry. A missing return can replace the useful result with None. A name says nothing about additional effects, argument changes, error handling or information written to logs.
In iterators and generators, another small syntax change will separate “prepare some work” from “perform it now”. That distinction will help you follow streamed framework results.