Skip to content

GH-117586: Speed up pathlib.Path.glob() by working with strings #117589

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 8 commits into from
Apr 10, 2024
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Ensure results are normalized.
  • Loading branch information
barneygale committed Apr 6, 2024
commit 824f1f682d6b07ad650e1a610a9369ea38be0b17
23 changes: 22 additions & 1 deletion Lib/pathlib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,25 @@ def _make_child_relpath(self, name):
path._tail_cached = tail + [name]
return path

def _make_glob_paths(self, paths):
"""Yields normalized path objects from the given iterable of string
glob results."""
sep = self.parser.sep
drive = self.drive
root = self.root
prefix = drive + root
prefix_len = len(prefix)
if not prefix_len and not self._tail_cached:
prefix_len = 2 # strip off leading "./"
for path in paths:
tail = path[prefix_len:].removesuffix(sep)
path = self.with_segments(path)
path._str = (prefix + tail) or '.'
path._drv = drive
path._root = root
path._tail_cached = tail.split(sep)
yield path

def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
"""Iterate over this subtree and yield all existing files (of any
kind, including directories) matching the given relative pattern.
Expand All @@ -622,7 +641,9 @@ def glob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
if not self.is_dir():
return iter([])
select = self._glob_selector(parts, case_sensitive, recurse_symlinks)
return map(self.with_segments, select(str(self), exists=True))
paths = select(str(self), exists=True)
paths = self._make_glob_paths(paths)
return paths

def rglob(self, pattern, *, case_sensitive=None, recurse_symlinks=False):
"""Recursively yield all existing files (of any kind, including
Expand Down