From 919f0bc8c904d3aa13eedb2dd1fe9c6b0555a591 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Mon, 21 Oct 2019 09:36:21 +0300 Subject: [PATCH] bpo-38208: Simplify string.Template by using __init_subclass__(). (GH-16256) --- Lib/string.py | 46 ++++++++++++++++++++++------------------------ 1 file changed, 22 insertions(+), 24 deletions(-) diff --git a/Lib/string.py b/Lib/string.py index b423ff5dc6..489777b10c 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -54,30 +54,7 @@ from collections import ChainMap as _ChainMap _sentinel_dict = {} -class _TemplateMetaclass(type): - pattern = r""" - %(delim)s(?: - (?P%(delim)s) | # Escape sequence of two delimiters - (?P%(id)s) | # delimiter and a Python identifier - {(?P%(bid)s)} | # delimiter and a braced identifier - (?P) # Other ill-formed delimiter exprs - ) - """ - - def __init__(cls, name, bases, dct): - super(_TemplateMetaclass, cls).__init__(name, bases, dct) - if 'pattern' in dct: - pattern = cls.pattern - else: - pattern = _TemplateMetaclass.pattern % { - 'delim' : _re.escape(cls.delimiter), - 'id' : cls.idpattern, - 'bid' : cls.braceidpattern or cls.idpattern, - } - cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) - - -class Template(metaclass=_TemplateMetaclass): +class Template: """A string class for supporting $-substitutions.""" delimiter = '$' @@ -89,6 +66,24 @@ class Template(metaclass=_TemplateMetaclass): braceidpattern = None flags = _re.IGNORECASE + def __init_subclass__(cls): + super().__init_subclass__() + if 'pattern' in cls.__dict__: + pattern = cls.pattern + else: + delim = _re.escape(cls.delimiter) + id = cls.idpattern + bid = cls.braceidpattern or cls.idpattern + pattern = fr""" + {delim}(?: + (?P{delim}) | # Escape sequence of two delimiters + (?P{id}) | # delimiter and a Python identifier + {{(?P{bid})}} | # delimiter and a braced identifier + (?P) # Other ill-formed delimiter exprs + ) + """ + cls.pattern = _re.compile(pattern, cls.flags | _re.VERBOSE) + def __init__(self, template): self.template = template @@ -146,6 +141,9 @@ class Template(metaclass=_TemplateMetaclass): self.pattern) return self.pattern.sub(convert, self.template) +# Initialize Template.pattern. __init_subclass__() is automatically called +# only for subclasses, not for the Template class itself. +Template.__init_subclass__() ######################################################################## -- 2.40.0