8000 gh-118761: Optimise import time for ``string`` by AA-Turner · Pull Request #132037 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-118761: Optimise import time for string #132037

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 8, 2025
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
Loading
0