classification
Title: string.Template should allow inspection of identifiers
Type: enhancement Stage:
Components: Library (Lib) Versions: Python 3.11
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: ben11kehoe
Priority: normal Keywords:

Created on 2022-01-08 20:12 by ben11kehoe, last changed 2022-01-08 20:12 by ben11kehoe.

Messages (1)
msg410112 - (view) Author: Ben Kehoe (ben11kehoe) Date: 2022-01-08 20:12
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.
History
Date User Action Args
2022-01-08 20:12:29ben11kehoecreate