format_map Fills Missing Keys Safely

Render templates whose keys may be missing by pairing format_map with a __missing__ fallback instead of letting KeyError abort the whole render.

PythonConfig Management

Code

pythonsnippet
18 lines
class Lenient(dict):
    """missing keys 渲染成显式占位符,而不是抛 KeyError 中断渲染。"""

    def __missing__(self, key):
        return '<missing:' + key + '>'


template = 'deploy {env} build {build_id} by {user}'

# 普通字典缺键直接抛 KeyError
try:
    template.format_map({'env': 'prod', 'build_id': '941'})
except KeyError as exc:
    print('plain dict:', exc, 'is missing')

# __missing__ 兜底后缺什么一目了然
print('lenient :', template.format_map(Lenient(env='prod', build_id='941')))
print('complete:', template.format_map(Lenient(env='prod', build_id='941', user='ci-bot')))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

plain dict: 'user' is missing
lenient : deploy prod build 941 by <missing:user>
complete: deploy prod build 941 by ci-bot

Inside the snippet

Count the class Lenient and the function __missing__ as the entire surface area of format_map Fills Missing Keys Safely.

Putting it to use

Signature: def __missing__(self, key)

Running the file prints labeled results such as plain dict:, lenient :, complete: — each operation’s effect is visible in the output.

Core lines

def __missing__(self, key):
    return '<missing:' + key + '>'
except KeyError as exc:
    print('plain dict:', exc, 'is missing')

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `__missing__` at load time.