summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBarney Gale <barney.gale@gmail.com>2023-11-25 17:41:05 (GMT)
committerGitHub <noreply@github.com>2023-11-25 17:41:05 (GMT)
commitbbb4367b55ead1a0322d86b568c6c4607f539d3e (patch)
treebd3f0371d562e6772df0a7c5334329a9230ffaf8
parentfbb9027a037ff1bfaf3f596df033ca45743ee980 (diff)
downloadcpython-bbb4367b55ead1a0322d86b568c6c4607f539d3e.zip
cpython-bbb4367b55ead1a0322d86b568c6c4607f539d3e.tar.gz
cpython-bbb4367b55ead1a0322d86b568c6c4607f539d3e.tar.bz2
GH-77621: Delay some imports from pathlib (#112244)
Import `contextlib`, `glob` and `re` only as required. Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
-rw-r--r--Lib/pathlib.py14
-rw-r--r--Misc/NEWS.d/next/Library/2023-11-21-02-58-14.gh-issue-77621.MYv5XS.rst2
2 files changed, 11 insertions, 5 deletions
diff --git a/Lib/pathlib.py b/Lib/pathlib.py
index 32ccf81..0e01099 100644
--- a/Lib/pathlib.py
+++ b/Lib/pathlib.py
@@ -5,14 +5,11 @@ paths with operations that have semantics appropriate for different
operating systems.
"""
-import contextlib
import functools
-import glob
import io
import ntpath
import os
import posixpath
-import re
import sys
import warnings
from _collections_abc import Sequence
@@ -75,17 +72,23 @@ def _is_case_sensitive(pathmod):
# Globbing helpers
#
+re = glob = None
+
@functools.lru_cache(maxsize=256)
def _compile_pattern(pat, sep, case_sensitive):
"""Compile given glob pattern to a re.Pattern object (observing case
sensitivity)."""
+ global re, glob
+ if re is None:
+ import re, glob
+
flags = re.NOFLAG if case_sensitive else re.IGNORECASE
regex = glob.translate(pat, recursive=True, include_hidden=True, seps=sep)
# The string representation of an empty path is a single dot ('.'). Empty
# paths shouldn't match wildcards, so we consume it with an atomic group.
regex = r'(\.\Z)?+' + regex
- return re.compile(regex, flags).match
+ return re.compile(regex, flags=flags).match
def _select_children(parent_paths, dir_only, follow_symlinks, match):
@@ -981,7 +984,8 @@ class _PathBase(PurePath):
def _scandir(self):
# Emulate os.scandir(), which returns an object that can be used as a
# context manager. This method is called by walk() and glob().
- return contextlib.nullcontext(self.iterdir())
+ from contextlib import nullcontext
+ return nullcontext(self.iterdir())
def _make_child_relpath(self, name):
path_str = str(self)
diff --git a/Misc/NEWS.d/next/Library/2023-11-21-02-58-14.gh-issue-77621.MYv5XS.rst b/Misc/NEWS.d/next/Library/2023-11-21-02-58-14.gh-issue-77621.MYv5XS.rst
new file mode 100644
index 0000000..f3e6efc
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2023-11-21-02-58-14.gh-issue-77621.MYv5XS.rst
@@ -0,0 +1,2 @@
+Slightly improve the import time of the :mod:`pathlib` module by deferring
+some imports. Patch by Barney Gale.