Index: Doc/library/string.rst =================================================================== --- Doc/library/string.rst (révision 88911) +++ Doc/library/string.rst (copie de travail) @@ -650,9 +650,11 @@ these rules. The methods of :class:`Template` are: -.. class:: Template(template) +.. class:: Template(template, default={}) - The constructor takes a single argument which is the template string. + The constructor takes two arguments, the first is the template string and + the second (optional) is a dictionary object which specify which values + should be used as default values, if no provided. .. method:: substitute(mapping, **kwds) @@ -667,10 +669,10 @@ .. method:: safe_substitute(mapping, **kwds) Like :meth:`substitute`, except that if placeholders are missing from - *mapping* and *kwds*, instead of raising a :exc:`KeyError` exception, the - original placeholder will appear in the resulting string intact. Also, - unlike with :meth:`substitute`, any other appearances of the ``$`` will - simply return ``$`` instead of raising :exc:`ValueError`. + *mapping*, *kwds* and *default*, instead of raising a :exc:`KeyError` + exception, the original placeholder will appear in the resulting string + intact. Also, unlike with :meth:`substitute`, any other appearances of + the ``$`` will simply return ``$`` instead of raising :exc:`ValueError`. While other exceptions may still occur, this method is called "safe" because substitutions always tries to return a usable string instead of @@ -679,13 +681,18 @@ templates containing dangling delimiters, unmatched braces, or placeholders that are not valid Python identifiers. - :class:`Template` instances also provide one public data attribute: + :class:`Template` instances also provide two public data attributes: .. attribute:: template This is the object passed to the constructor's *template* argument. In general, you shouldn't change it, but read-only access is not enforced. + .. attribute:: default + + This is the optional dictionary object passed to the constructor's + *template* argument. + Here is an example of how to use a Template: >>> from string import Template Index: Lib/string.py =================================================================== --- Lib/string.py (révision 88911) +++ Lib/string.py (copie de travail) @@ -77,8 +77,9 @@ idpattern = r'[_a-z][_a-z0-9]*' flags = _re.IGNORECASE - def __init__(self, template): + def __init__(self, template, default={}): self.template = template + self.default = default # Search for $$, $identifier, ${identifier}, and any bare $'s @@ -97,12 +98,14 @@ def substitute(self, *args, **kws): if len(args) > 1: raise TypeError('Too many positional arguments') + + mapping = self.default if not args: - mapping = kws + mapping.update(kws) elif kws: - mapping = ChainMap(kws, args[0]) + mapping.update(ChainMap(kws, args[0])) else: - mapping = args[0] + mapping.update(args[0]) # Helper function for .sub() def convert(mo): # Check the most common path first.