具有默认值的python模板

标签 python python-2.7

在 python 中我可以使用一个模板

from string import Template
templ = Template('hello ${name}')
print templ.substitute(name='world')

如何在模板中定义默认值? 并在没有任何值的情况下调用模板。

print templ.substitute()
编辑

当我不带参数调用时获取默认值,示例

 print templ.substitute()
 >> hello name

最佳答案

Template.substitute 方法采用 mapping argument in addition to keyword arguments .关键字参数覆盖 mapping 位置参数提供的参数,这使得 mapping 成为实现默认值的自然方式,无需子类化:

from string import Template
defaults = { "name": "default" }
templ = Template('hello ${name}')
print templ.substitute(defaults)               # prints hello default
print templ.substitute(defaults, name="world") # prints hello world

这也适用于 safe_substitute:

print templ.safe_substitute()                       # prints hello ${name}
print templ.safe_substitute(defaults)               # prints hello default
print templ.safe_substitute(defaults, name="world") # prints hello world

如果您绝对坚持不向 substitute 传递任何参数,您可以子类化模板:

class DefaultTemplate(Template):
    def __init__(self, template, default):
        self.default = default
        super(DefaultTemplate, self).__init__(template)

    def mapping(self, mapping):
        default_mapping = self.default.copy()
        default_mapping.update(mapping)
        return default_mapping

    def substitute(self, mapping=None, **kws):
        return super(DefaultTemplate, self).substitute(self.mapping(mapping or {}), **kws)

    def substitute(self, mapping=None, **kws):
        return super(DefaultTemplate, self).safe_substitute(self.mapping(mapping or {}), **kws)

然后像这样使用它:

DefaultTemplate({ "name": "default" }).substitute()

尽管我发现这比仅传递一个默认为 substitutemapping 更不明确且可读性较差。

关于具有默认值的python模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160798/

相关文章:

python - 如何通过 id discord.py 获取消息

Python 3 无法pickle lambda

python - 为什么列表元素查找在 Python 中是 O(1)?

使用 NumPy 数据类型的 Python 字典查找速度

python - 是否有可能从 eggs 中的 Python 回溯中获取行?

python-2.7 - 为什么重新分配 pandas DataFrame 不会触发SettingWithCopyWarning?

python - 如何通过python中的beautiful soup在html页面中找到特定的单词?

python - 在 Python 中, else :continue in a try. .except block 的用途是什么?

python - 文本对齐 : extracting matching sequence using python

Python,重新启动整个代码,以便移动对象和所有内容(不仅仅是循环,而是整个代码)