← 中文资源

简体中文版本

format_map 安全补齐缺失键

模板键可能缺失时别让 KeyError 中断渲染:给字典实现 __missing__ 再交给 format_map,缺什么键会以显式占位符呈现。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

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')))