Skip to content

Commit 98ce7b1

Browse files
authored
bpo-41006: pkgutil imports lazily re (GH-20939)
The pkgutil module now imports lazily the re module to speedup Python startup time.
1 parent 7824cc0 commit 98ce7b1

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

Lib/pkgutil.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import importlib.machinery
88
import os
99
import os.path
10-
import re
1110
import sys
1211
from types import ModuleType
1312
import warnings
@@ -638,9 +637,7 @@ def get_data(package, resource):
638637
return loader.get_data(resource_name)
639638

640639

641-
_DOTTED_WORDS = r'(?!\d)(\w+)(\.(?!\d)(\w+))*'
642-
_NAME_PATTERN = re.compile(f'^(?P<pkg>{_DOTTED_WORDS})(?P<cln>:(?P<obj>{_DOTTED_WORDS})?)?$', re.U)
643-
del _DOTTED_WORDS
640+
_NAME_PATTERN = None
644641

645642
def resolve_name(name):
646643
"""
@@ -674,6 +671,15 @@ def resolve_name(name):
674671
AttributeError - if a failure occurred when traversing the object hierarchy
675672
within the imported package to get to the desired object)
676673
"""
674+
global _NAME_PATTERN
675+
if _NAME_PATTERN is None:
676+
# Lazy import to speedup Python startup time
677+
import re
678+
dotted_words = r'(?!\d)(\w+)(\.(?!\d)(\w+))*'
679+
_NAME_PATTERN = re.compile(f'^(?P<pkg>{dotted_words})'
680+
f'(?P<cln>:(?P<obj>{dotted_words})?)?$',
681+
re.UNICODE)
682+
677683
m = _NAME_PATTERN.match(name)
678684
if not m:
679685
raise ValueError(f'invalid format: {name!r}')

0 commit comments

Comments
 (0)