Skip to content

GH-117841: Speed up pathlib.Path.glob() on Windows by using lexists() #117858

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

Closed
wants to merge 2 commits into from
Closed
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
12 changes: 4 additions & 8 deletions Lib/glob.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,7 @@ def __init__(self, sep, case_sensitive, case_pedantic=False, recursive=False):

# Low-level methods

lstat = staticmethod(os.lstat)
lexists = staticmethod(os.path.lexists)
scandir = staticmethod(os.scandir)
parse_entry = operator.attrgetter('path')
concat_path = operator.add
Expand Down Expand Up @@ -510,14 +510,10 @@ def select_exists(self, path, exists=False):
"""
if exists:
# Optimization: this path is already known to exist, e.g. because
# it was returned from os.scandir(), so we skip calling lstat().
# it was returned from os.scandir(), so we skip calling lexists().
yield path
elif self.lexists(path):
yield path
else:
try:
self.lstat(path)
yield path
except OSError:
pass

@classmethod
def walk(cls, root, top_down, on_error, follow_symlinks):
Expand Down
10 changes: 9 additions & 1 deletion Lib/pathlib/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,17 @@ def _is_case_sensitive(parser):


class Globber(glob._Globber):
lstat = operator.methodcaller('lstat')
add_slash = operator.methodcaller('joinpath', '')

@staticmethod
def lexists(path):
# Emulate os.path.lexists(), which never raises OSError.
try:
path.stat(follow_symlinks=False)
except (OSError, ValueError):
return False
return True

@staticmethod
def scandir(path):
# Emulate os.scandir(), which returns an object that can be used as a
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Speed up :meth:`pathlib.Path.glob` on Windows by using fast implementation
of :func:`os.path.lexists`.
Loading