Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python template with default value

In python I can use a template with

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

how can I define a default value in the template? And call the template without any value.

print templ.substitute()
Edit

And when I call without parameters get the default value, example

 print templ.substitute()
 >> hello name
like image 386
JuanPablo Avatar asked Jul 03 '18 18:07

JuanPablo


1 Answers

The Template.substitute method takes a mapping argument in addition to keyword arguments. The keyword arguments override the arguments provided by the mapping positional argument, which makes mapping a natural way to implement defaults without needing to subclass:

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

This will also work for 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

If you are absolutely insistent on passing no arguments to substitute you could subclass Template:

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)

And then use it like this:

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

Although I find this to be less explicit and less readable than just passing a mapping with defaults to substitute.

like image 184
Matthew Story Avatar answered Nov 15 '22 00:11

Matthew Story