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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With