Skip to content

Commit ab8fe83

Browse files
barneygaleAlexWaygood
authored andcommitted
pythonGH-77621: Delay some imports from pathlib (python#112244)
Import `contextlib`, `glob` and `re` only as required. Co-authored-by: Alex Waygood <[email protected]>
1 parent e2f3f28 commit ab8fe83

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

Lib/pathlib.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,11 @@
55
operating systems.
66
"""
77

8-
import contextlib
98
import functools
10-
import glob
119
import io
1210
import ntpath
1311
import os
1412
import posixpath
15-
import re
1613
import sys
1714
import warnings
1815
from _collections_abc import Sequence
@@ -75,17 +72,23 @@ def _is_case_sensitive(pathmod):
7572
# Globbing helpers
7673
#
7774

75+
re = glob = None
76+
7877

7978
@functools.lru_cache(maxsize=256)
8079
def _compile_pattern(pat, sep, case_sensitive):
8180
"""Compile given glob pattern to a re.Pattern object (observing case
8281
sensitivity)."""
82+
global re, glob
83+
if re is None:
84+
import re, glob
85+
8386
flags = re.NOFLAG if case_sensitive else re.IGNORECASE
8487
regex = glob.translate(pat, recursive=True, include_hidden=True, seps=sep)
8588
# The string representation of an empty path is a single dot ('.'). Empty
8689
# paths shouldn't match wildcards, so we consume it with an atomic group.
8790
regex = r'(\.\Z)?+' + regex
88-
return re.compile(regex, flags).match
91+
return re.compile(regex, flags=flags).match
8992

9093

9194
def _select_children(parent_paths, dir_only, follow_symlinks, match):
@@ -981,7 +984,8 @@ def iterdir(self):
981984
def _scandir(self):
982985
# Emulate os.scandir(), which returns an object that can be used as a
983986
# context manager. This method is called by walk() and glob().
984-
return contextlib.nullcontext(self.iterdir())
987+
from contextlib import nullcontext
988+
return nullcontext(self.iterdir())
985989

986990
def _make_child_relpath(self, name):
987991
path_str = str(self)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Slightly improve the import time of the :mod:`pathlib` module by deferring
2+
some imports. Patch by Barney Gale.

0 commit comments

Comments
 (0)