https://github.com/python/cpython/commit/cf5e438c0297954c4411c1c3ae4ba67a48b134ea
commit: cf5e438c0297954c4411c1c3ae4ba67a48b134ea
branch: main
author: Semyon Moroz <donbar...@proton.me>
committer: hugovk <1324225+hug...@users.noreply.github.com>
date: 2025-03-27T15:47:08+02:00
summary:

gh-118761: Always lazy import `re` in `locale` (#129860)

files:
A Misc/NEWS.d/next/Library/2025-02-08-21-37-05.gh-issue-118761.EtqxeB.rst
M Lib/locale.py

diff --git a/Lib/locale.py b/Lib/locale.py
index 213d5e93418cfb..2feb10e59c96a3 100644
--- a/Lib/locale.py
+++ b/Lib/locale.py
@@ -13,7 +13,6 @@
 import sys
 import encodings
 import encodings.aliases
-import re
 import _collections_abc
 from builtins import str as _builtin_str
 import functools
@@ -177,8 +176,7 @@ def _strip_padding(s, amount):
         amount -= 1
     return s[lpos:rpos+1]
 
-_percent_re = re.compile(r'%(?:\((?P<key>.*?)\))?'
-                         r'(?P<modifiers>[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')
+_percent_re = None
 
 def _format(percent, value, grouping=False, monetary=False, *additional):
     if additional:
@@ -217,6 +215,13 @@ def format_string(f, val, grouping=False, monetary=False):
     Grouping is applied if the third parameter is true.
     Conversion uses monetary thousands separator and grouping strings if
     forth parameter monetary is true."""
+    global _percent_re
+    if _percent_re is None:
+        import re
+
+        _percent_re = re.compile(r'%(?:\((?P<key>.*?)\))?(?P<modifiers'
+                                 r'>[-#0-9 +*.hlL]*?)[eEfFgGdiouxXcrs%]')
+
     percents = list(_percent_re.finditer(f))
     new_f = _percent_re.sub('%s', f)
 
diff --git 
a/Misc/NEWS.d/next/Library/2025-02-08-21-37-05.gh-issue-118761.EtqxeB.rst 
b/Misc/NEWS.d/next/Library/2025-02-08-21-37-05.gh-issue-118761.EtqxeB.rst
new file mode 100644
index 00000000000000..b35275b321b4b2
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-02-08-21-37-05.gh-issue-118761.EtqxeB.rst
@@ -0,0 +1,2 @@
+Improve import time of :mod:`locale` using lazy import ``re``. Patch by
+Semyon Moroz.

_______________________________________________
Python-checkins mailing list -- python-checkins@python.org
To unsubscribe send an email to python-checkins-le...@python.org
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: arch...@mail-archive.com

Reply via email to