Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Doc/library/string.rst
Original file line number Diff line number Diff line change
Expand Up @@ -943,7 +943,8 @@ attributes:

Alternatively, you can provide the entire regular expression pattern by
overriding the class attribute *pattern*. If you do this, the value must be a
regular expression object with four named capturing groups. The capturing
regular expression pattern string, or a compiled regular expression
object, with four named capturing groups. The capturing
groups correspond to the rules given above, along with the invalid placeholder
rule:

Expand Down
5 changes: 5 additions & 0 deletions Lib/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ def __init_subclass__(cls):
super().__init_subclass__()
if 'pattern' in cls.__dict__:
pattern = cls.pattern
if isinstance(pattern, _re.Pattern):
# An already-compiled pattern (which the documentation allows)
# is used as-is; re.compile() rejects flags on a compiled
# pattern.
return
else:
delim = _re.escape(cls.delimiter)
id = cls.idpattern
Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,20 @@ def test_SafeTemplate(self):
eq(s.safe_substitute(dict(who='tim', what='ham', meal='dinner')),
'tim likes ham for dinner')

def test_precompiled_pattern(self):
# A subclass may supply an already-compiled pattern; it must be reused,
# not recompiled (re.compile() rejects flags on a compiled pattern).
import re
compiled = re.compile(
r'\$(?:(?P<escaped>\$)|(?P<named>[a-z]+)|'
r'\{(?P<braced>[a-z]+)\}|(?P<invalid>))')
class MyTemplate(Template):
pattern = compiled
self.assertIs(MyTemplate.pattern, compiled)
self.assertEqual(
MyTemplate('$who likes $what').substitute(who='tim', what='ham'),
'tim likes ham')

def test_invalid_placeholders(self):
raises = self.assertRaises
s = Template('$who likes $')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :class:`string.Template` raising a spurious :exc:`ValueError` when the
*pattern* attribute is a compiled regular expression object, which the
documentation allows.
Loading