Batu Lab NotesPractical developer guides

Build a keyed formatter with partial

By Batu ยท English technical notes

Also published in our Blogger archive.

functools.partial creates a callable with selected arguments already bound. release_line freezes the template argument of render(), leaving a compact formatter that accepts only the named values needed for that template. Calling it with build="A17" and result="passed" passes those keyword values through to render(), where str.format_map() resolves the {build} and {result} fields from the fields dictionary.

The positional-only slash in render(template, /, **fields) matters here. It reserves the first parameter for the template and prevents a field named template from conflicting with it. The assertion on release_line.func confirms that the partial object wraps render, while the message assertion confirms the exact completed string.

A missing required field raises KeyError; for example, calling release_line(build="A17") has no result value to substitute. Extra supplied fields are harmless because format_map() only reads fields referenced by the template. Literal braces must be doubled as {{ and }}, and untrusted templates can expose attributes or mapping keys you did not intend to format. Keep templates application-controlled when output crosses a trust boundary.

AI assistance helped prepare this Batu Lab Notes article.

from functools import partial


def render(template, /, **fields):
    return template.format_map(fields)


release_line = partial(render, "build={build}; result={result}")
message = release_line(build="A17", result="passed")
assert message == "build=A17; result=passed"
assert release_line.func is render
print(message)

Expected stdout:

build=A17; result=passed

Sources