[New-bugs-announce] [issue46307] string.Template should allow inspection of identifiers

Ben Kehoe report at bugs.python.org
Sat Jan 8 15:12:29 EST 2022


New submission from Ben Kehoe <ben at kehoe.io>:

Currently, the only thing that can be done with a string.Template instance and a mapping is either attempt to substitute with substitute() and catch a KeyError if some identifier has not been provided in the mapping, or substitute with safe_substitute() and not know whether all identifiers were provided.

I propose adding a method that returns the identifiers in the template. Because the template string and pattern are exposed, this is already possible as a separate function:

def get_identifiers(template):
    return list(
        set(
            filter(
                lambda v: v is not None,
                (mo.group('named') or mo.group('braced') 
                 for mo in template.pattern.finditer(template.template))
            )
        )
    )

However, this function is not easy for a user of string.Template to construct without learning how the template pattern works (which is documented but intended to be learned only when subclassing or modifying id patterns).

As a method on string.Template, this would enable use cases like more comprehensive error handling (e.g., finding all missing mapping keys at once) or interactive prompting.

----------
components: Library (Lib)
messages: 410112
nosy: ben11kehoe
priority: normal
severity: normal
status: open
title: string.Template should allow inspection of identifiers
type: enhancement
versions: Python 3.11

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46307>
_______________________________________


More information about the New-bugs-announce mailing list