Skip to content

GH-77621: Delay some imports from pathlib #112244

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 3 commits into from
Nov 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
14 changes: 9 additions & 5 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@
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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -989,7 +992,8 @@ def iterdir(self):
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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Slightly improve the import time of the :mod:`pathlib` module by deferring
some imports. Patch by Barney Gale.