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.
Code
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-botInside 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. The file defines `__missing__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.