Skip to content
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Make _TemplatePattern a singleton
  • Loading branch information
AA-Turner committed Apr 7, 2025
commit bb3605a7d89acb288cabdf5e29dffc11b2567251
7 changes: 4 additions & 3 deletions Lib/string.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,12 @@ def capwords(s, sep=None):


class _TemplatePattern:
# This descriptor is overwritten in ``Template._compile_pattern()``.
def __get__(self, instance, cls=None):
if cls is None:
return self
# This descriptor is overwritten in ``_compile_pattern()``.
return cls._compile_pattern()
_TemplatePattern = _TemplatePattern()


class Template:
Expand All @@ -72,7 +73,7 @@ class Template:
braceidpattern = None
flags = None # default: re.IGNORECASE

pattern = _TemplatePattern() # use a descriptor to compile the pattern
pattern = _TemplatePattern # use a descriptor to compile the pattern

def __init_subclass__(cls):
super().__init_subclass__()
Expand All @@ -83,7 +84,7 @@ def _compile_pattern(cls):
import re # deferred import, for performance

cls_pattern = cls.__dict__.get('pattern')
if cls_pattern and not isinstance(cls_pattern, _TemplatePattern):
if cls_pattern is not None and cls_pattern is not _TemplatePattern:
# Prefer a pattern defined on the class.
pattern = cls_pattern
else:
Expand Down