Skip to content

Recognize ${braced} variables in template extract_vars#1455

Open
c-tonneslan wants to merge 1 commit into
simonw:mainfrom
c-tonneslan:fix/template-braced-vars
Open

Recognize ${braced} variables in template extract_vars#1455
c-tonneslan wants to merge 1 commit into
simonw:mainfrom
c-tonneslan:fix/template-braced-vars

Conversation

@c-tonneslan
Copy link
Copy Markdown

Template.extract_vars only collects the named group from string.Template's match:

return [
    match.group("named")
    for match in string_template.pattern.finditer(string_template.template)
    if match.group("named")
]

But string.Template matches a variable as either $named or ${braced}, and both forms are valid. So ${var} placeholders are invisible to extract_vars, with two consequences:

  • Template.vars() under-reports — Template(name="x", prompt="Hello ${name}").vars() returns set() instead of {"name"}.
  • interpolate()'s missing-variable check never sees them, so a template using ${missing} raises a raw KeyError out of string.Template.substitute() instead of the intended Template.MissingVariables error.
>>> Template.interpolate("Hi ${who}", {})
KeyError: 'who'          # expected: MissingVariables: Missing variables: who

Fix collects the braced group too. Added ${braced} cases (resolve, missing, and mixed $a + ${b}) to the existing test_template_evaluate parametrize list — the missing-variable case fails on main with a raw KeyError and passes with the fix. Full test_templates.py (49 tests) green.

extract_vars only collected the `named` group from string.Template's
match, so ${var} placeholders were invisible to it. string.Template
matches a variable as either $named or ${braced}, and both are valid.

Two consequences: Template.vars() under-reported, missing any ${var};
and interpolate()'s MissingVariables check never saw them, so a
template using ${missing} raised a raw KeyError from substitute()
instead of the intended MissingVariables error.

Collect the `braced` group as well.

Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant