gh-78318: Add pathlib.Path.lexists and related by nphilipp · Pull Request #21157 · python/cpython · GitHub
Skip to content
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
17 changes: 15 additions & 2 deletions Doc/library/pathlib.rst
18 changes: 16 additions & 2 deletions Lib/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,12 +1061,18 @@ def hardlink_to(self, target):

# Convenience functions for querying the stat results

def exists(self):
def exists(self, *, follow_symlinks=True):
"""
Whether this path exists.

Returns False for broken symbolic links unless follow_symlinks is set
to False.
"""
try:
self.stat()
if follow_symlinks:
self.stat()
else:
self.lstat()
except OSError as e:
if not _ignore_error(e):
raise
Expand Down Expand Up @@ -1200,6 +1206,14 @@ def is_socket(self):
# Non-encodable path
return False

def lexists(self):
"""
Whether this path exists, but don't follow symbolic links.

Returns True for broken symbolic links.
"""
return self.exists(follow_symlinks=False)

def expanduser(self):
""" Return a new path with expanded ~ and ~user constructs
(as returned by os.path.expanduser)
Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1646,11 +1646,31 @@ def test_exists(self):
self.assertIs(True, (p / 'linkB').exists())
self.assertIs(True, (p / 'linkB' / 'fileB').exists())
self.assertIs(False, (p / 'linkA' / 'bah').exists())
self.assertIs(False, (p / 'brokenLink').exists())
self.assertIs(False, (p / 'brokenLinkLoop').exists())
self.assertIs(True, (p / 'brokenLink').exists(
follow_symlinks=False))
self.assertIs(True, (p / 'brokenLinkLoop').exists(
follow_symlinks=False))
self.assertIs(False, (p / 'foo').exists())
self.assertIs(False, P('/xyzzy').exists())
self.assertIs(False, P(BASE + '\udfff').exists())
self.assertIs(False, P(BASE + '\x00').exists())

@os_helper.skip_unless_symlink
def test_exists_follow_symlinks(self):
P = self.cls
p = P(BASE)
self.assertIs(True, (p / 'brokenLink').exists(follow_symlinks=False))
self.assertIs(True, (p / 'brokenLinkLoop').exists(follow_symlinks=False))

@os_helper.skip_unless_symlink
def test_lexists(self):
P = self.cls
p = P(BASE)
self.assertIs(True, (p / 'brokenLink').lexists())
self.assertIs(True, (p / 'brokenLinkLoop').lexists())

def test_open_common(self):
p = self.cls(BASE)
with (p / 'fileA').open('r') as f:
Expand Down