实现说明
Lenient和函数 __missing__承载全部实现。
使用要点
- 每一步打印都带着自己的标签:
plain dict:、lenient :、complete:。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 文件在加载时定义 __missing__。
入口签名:def __missing__(self, key)
核心语句
def __missing__(self, key):
return '<missing:' + key + '>'
except KeyError as exc:
print('plain dict:', exc, 'is missing')
代码示例
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')))