Debug Three Injected Defects in an Open-Source Template Engine
System DesignModel answerLast updated
Track down and fix three bugs in a Python template library: a silent AST visitor gap, a directory/file confusion in template lookup, and comment-only blocks that generate invalid Python.
You are handed a fork of a Python template library — one that compiles templates into Python modules and renders them by calling generated functions. Three defects have been deliberately introduced. Your job is to find each one, apply the smallest correct fix, and add a regression test. Narrate your reasoning as you go.
Library Primer
- Compilation model. Each template is translated into a Python source file. Rendering means importing that module and calling a function in it.
- Control lines. A line whose first non-whitespace character is
%becomes a Python statement:% if,% for,% elif,% else,% endif,% endfor, etc. - Template comments. A line whose first non-whitespace characters are
##is erased at compile time and produces nothing — no Python output, no rendered output. - Embedded Python.
${expr}interpolates an expression. Tag attributes such as<%def name="greet(name, punct='!')">declare callables whose signatures are real Python syntax. The library parses those signatures with the standardastmodule and walks the resulting trees withast.NodeVisitorsubclasses. - Template lookup. A
TemplateLookupis initialised with an ordered list of directories. Given a template name like/emails/welcome.txtit searches each directory in turn, resolves the path, checks that a file exists there, and returns it.
Constraints
- There are exactly three defects, one per Part below.
- Each fix should be minimal and local — match the surrounding code style and do not alter any behavior that is currently correct.
- Part 1 names the missing code and asks you to explain consequences. Parts 2 and 3 describe a symptom and ask you to trace it to its cause.
- When all three fixes are applied the full existing test suite must pass.
Useful Clarifying Questions to Consider
- Do existing failing tests map one-to-one onto the defects, or must some be discovered from symptoms?
- Which Python versions must be supported? AST node types change across releases (e.g.,
ast.argwas introduced in Python 3; keyword-only args, positional-only args, and type annotations each add their own nodes). - When one lookup directory contains a folder named
emailsand a later directory contains a file namedemails, which one should win — and what should happen when neither directory contains a file? - Should a control block whose entire body consists of comment lines behave identically to a genuinely empty block, for every control form (
if,else,elif,for,while, nested blocks)?
Part 1 — Silent gap in the AST argument visitor
One ast.NodeVisitor subclass in the library is missing its visit_arg method.
- Explain exactly which Python constructs cause the
astmodule to emitast.argnodes. - Describe how
ast.NodeVisitordispatches: what it does when it encounters a node type for which novisit_*method exists, and why this particular gap does not raise an exception. - Explain the concrete job this visitor is doing (e.g., collecting names, checking for conflicts) and how that job goes wrong when argument nodes are silently skipped.
- Restore the missing method and write at least one test that would have caught the removal — both a unit test against the visitor directly and a template-level integration test.
Focus areas: visitor dispatch mechanics, every parameter kind that produces ast.arg nodes (positional, default, keyword-only, *args, **kwargs, positional-only, annotated), the silent failure mode, and test design.
Part 2 — Directory path mistaken for a template file
When a template name resolves to a directory rather than a file inside one of the lookup directories, the library raises a low-level OS error (something like IsADirectoryError or a permission error, depending on platform) instead of its own "template not found" error.
- Find the predicate that decides whether a resolved path is a valid template file, and show exactly what it currently checks vs. what it should check.
- Trace the behavior across multiple lookup directories: a directory that should be skipped, a later directory that contains the real file, and the case where no directory contains a matching file.
- Describe at least one alternative fix and explain why your chosen fix is preferable (think: clarity, portability, behavior on edge cases).
- Write tests that construct a temporary directory tree, place a folder and a file at the relevant paths, and assert the correct outcome for each scenario.
Focus areas: os.path predicates, lookup ordering, the library's own "not found" exception type, and temporary-directory test setup.
Part 3 — Control block whose body is only comments fails to compile
The following template is semantically valid — the comment is intentional and the block should simply produce no output — but compiling it raises a SyntaxError inside the generated Python module:
% if show_banner:
## banner removed until the redesign ships
% endif
Welcome
- Show what Python source the code generator emits for this template, and explain why it is syntactically invalid.
- Find the place in the generator where it decides to insert a
passstatement into an otherwise-empty block, and identify which node types it already treats as "producing no content" and which type it is missing. - Identify every other control form that the same omission breaks:
% elsebranches with only comments,% elifbranches,% forloops, nested% ifblocks, etc. - Fix the generator and add template-level tests that compile and render each affected control form.
Focus areas: Python block syntax requirements, how the template compiler represents comment nodes vs. text nodes vs. statement nodes, and the precise condition that gates pass insertion.
Hints
Hint 1
For Part 1, print out what ast.parse produces for a function signature like `def f(a, b=1, *args, kw_only=2, **kwargs)` and trace each node type the visitor would encounter. Then check what generic_visit does — and what it doesn't do — to see why nothing blows up.
Hint 2
For Part 2, `os.path.isfile` is the key predicate: it returns False for directories and for paths that don't exist, so replacing an existence check with `isfile` simultaneously handles the directory case and the missing-file case in one go.
Hint 3
For Part 3, look at the generated Python source directly (most template libraries expose a way to dump it) for a block containing only a comment line. A Python `if` body cannot be empty — it needs at least one statement — so look for the `pass`-insertion logic and check which internal node types it counts as 'empty'.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Workflow
Before touching any code, run the full test suite and read the output. Group failures by symptom. Then reproduce each defect in isolation — a five-line script is faster than re-running the whole suite every time. Read tracebacks and, for Part 3, dump the generated Python source directly; guessing at template compiler internals without reading the output is how debugging sessions stall.
Part 1 — Missing visit_arg in an AST visitor
How ast.NodeVisitor dispatches
NodeVisitor.visit(node) looks up "visit_" + type(node).__name__ on the instance. If it finds the method it calls it. If it does not, it falls back to generic_visit, which simply recurses into child nodes without taking any action on the current node. This means a missing visit_arg never raises an exception — the visitor just walks past every ast.arg node silently.
Which constructs produce ast.arg nodes
In Python 3, ast.arg is the node type for every parameter in a function signature: ordinary positional parameters, parameters with defaults, keyword-only parameters (those after a bare *), the *args collector, the **kwargs collector, positional-only parameters (those before a /), and any parameter that carries a type annotation. So def f(a, b=1, /, c=2, *args, kw=3, **kw2) produces eight ast.arg nodes, each carrying a .arg string (the name) and optionally an .annotation.
What the visitor is doing and why the gap matters
The visitor in question collects or validates the set of names visible inside a template callable — for example to detect conflicts between argument names and template-level names, or to register those names so later expression nodes can reference them. When visit_arg is absent, every argument name is silently skipped. The collected name set is incomplete. The consequence depends on what the visitor feeds into: at minimum, argument names may not be reserved, so the library can generate code that shadows or conflicts with them; at worst, templates with non-trivial signatures render incorrectly or raise NameError at render time.
The fix
def visit_arg(self, node):
# ast.arg carries the parameter name in node.arg (a string, not a Name node)
self._add_name(node.arg)
self.generic_visit(node) # descend into any annotation
The exact body mirrors whatever visit_Name does for the same bookkeeping. The call to generic_visit matters if annotations can themselves contain names the visitor needs to see.
Regression tests
import ast
def test_visitor_sees_all_arg_nodes():
src = "def f(pos, /, normal, *args, kw_only=1, **kwargs): pass"
tree = ast.parse(src)
v = TheLibraryVisitor()
v.visit(tree)
for name in ("pos", "normal", "args", "kw_only", "kwargs"):
assert name in v.collected_names, f"{name!r} was not collected"
def test_template_with_def_tag_and_all_param_kinds(tmp_path):
t = Template("<%def name=\"f(a, *args, kw=None, **kw2)\">${a}</%def>${f('x')}")
assert t.render() == "x"
Part 2 — Directory path confused with a template file
The faulty predicate
The lookup code resolves a candidate path and then checks whether it exists with something equivalent to os.path.exists(path). os.path.exists returns True for directories. So when emails/ is a folder inside the first lookup directory, the check passes, and the code proceeds to open emails/ as a file, which the OS refuses.
The fix
Replace the existence check with os.path.isfile(path):
# Before
if os.path.exists(candidate):
return candidate
# After
if os.path.isfile(candidate):
return candidate
isfile returns False for directories and for paths that do not exist at all, so a single predicate handles both the directory-shadow case and the missing-file case. The loop continues to the next directory, and if no directory yields a file the library raises its own TemplateLookupException rather than an OS error.
Behavior across multiple directories
| Directory 1 contains | Directory 2 contains | Expected outcome |
|---|---|---|
emails/ (folder) | emails.html (file) | Returns the file from directory 2 |
emails/ (folder) | nothing | Raises TemplateLookupException |
emails.html (file) | anything | Returns the file from directory 1 |
Alternative fix and why it's weaker
You could catch IsADirectoryError (and its Windows equivalent) at the open call and continue the loop. That works, but it's platform-dependent (Windows raises a different exception), it lets the code attempt the open before realising the path is wrong, and it obscures intent. The isfile fix is the right semantic: the lookup's job is to find a file, so it should check for a file.
Regression tests
import os, tempfile
def test_directory_shadows_file_in_later_directory(tmp_path):
d1 = tmp_path / "d1"
d2 = tmp_path / "d2"
(d1 / "emails").mkdir(parents=True) # folder in d1
(d2).mkdir()
(d2 / "emails").write_text("hello") # file in d2
lookup = TemplateLookup(directories=[str(d1), str(d2)])
t = lookup.get_template("emails")
assert t.render().strip() == "hello"
def test_directory_with_no_file_raises_not_found(tmp_path):
d1 = tmp_path / "d1"
(d1 / "emails").mkdir(parents=True)
lookup = TemplateLookup(directories=[str(d1)])
with pytest.raises(TemplateLookupException):
lookup.get_template("emails")
Part 3 — Comment-only block generates invalid Python
What the generator emits
For the template:
% if show_banner:
## banner removed until the redesign ships
% endif
the code generator strips the ## comment line entirely (it produces no output node), leaving the if block with no body. The emitted Python looks like:
if show_banner:
# (nothing here)
Python requires at least one statement in every block body. The file is syntactically invalid and compile() raises a SyntaxError.
Where pass insertion lives
The generator already handles the empty-block case — it inserts a pass statement when a block's child list contains no "content-producing" nodes. The bug is that the condition enumerates node types that produce content but omits the Comment (or equivalent internal) node type. Because a comment node is not on the exclusion list, a block containing only comments is not considered empty, so pass is not inserted, but the comment node itself produces no Python output, leaving the block body blank.
The fix
Add the comment node type to the set of node types that count as "producing no output":
# Before (pseudocode of the condition)
if all(isinstance(n, (TextNode, ...)) for n in block.body):
block.body.append(PassNode())
# After
if all(isinstance(n, (TextNode, CommentNode, ...)) for n in block.body):
block.body.append(PassNode())
The exact class names depend on the library's internal AST. The principle is: any node type that emits zero lines of Python must be counted as "empty" when deciding whether a pass is needed.
Other control forms affected
% else:or% elif cond:branch containing only##comments% forloops whose body is entirely comments- Nested
% ifblocks inside another block % while(if supported)
Regression tests
def test_if_block_with_only_comment_compiles_and_renders():
src = "% if True:\n## comment\n% endif\nok"
assert Template(src).render().strip() == "ok"
def test_else_branch_with_only_comment():
src = "% if False:\nno\n% else:\n## nothing\n% endif\nok"
assert Template(src).render().strip() == "ok"
def test_for_loop_with_only_comment():
src = "% for i in []:\n## empty\n% endfor\ndone"
assert Template(src).render().strip() == "done"
Common Mistakes
- Part 1: Forgetting that
ast.argis Python-3-only; in Python 2 argument names areast.Namenodes insideast.arguments. A fix that only addsvisit_argwill miss that if the library still supports Python 2. - Part 2: Patching the
opencall instead of the existence check — this fixes the symptom on Linux but breaks on Windows where the OS error has a different type. - Part 3: Inserting
passunconditionally whenever a##comment appears anywhere in the template, rather than only when the block body would otherwise be empty. That's too broad and changes behavior for non-empty blocks.