Skip to content

Commit 986da8e

Browse files
authored
bpo-39895: Move pathlib.Path.touch() implementation into the path accessor. (GH-18838)
1 parent 04732ca commit 986da8e

File tree

1 file changed

+18
-24
lines changed

1 file changed

+18
-24
lines changed

Lib/pathlib.py

+18-24
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,23 @@ def link(self, src, dst):
431431
def symlink(self, src, dst, target_is_directory=False):
432432
raise NotImplementedError("os.symlink() not available on this system")
433433

434-
utime = os.utime
434+
def touch(self, path, mode=0o666, exist_ok=True):
435+
if exist_ok:
436+
# First try to bump modification time
437+
# Implementation note: GNU touch uses the UTIME_NOW option of
438+
# the utimensat() / futimens() functions.
439+
try:
440+
os.utime(path, None)
441+
except OSError:
442+
# Avoid exception chaining
443+
pass
444+
else:
445+
return
446+
flags = os.O_CREAT | os.O_WRONLY
447+
if not exist_ok:
448+
flags |= os.O_EXCL
449+
fd = os.open(path, flags, mode)
450+
os.close(fd)
435451

436452
if hasattr(os, "readlink"):
437453
readlink = os.readlink
@@ -1100,13 +1116,6 @@ def _opener(self, name, flags, mode=0o666):
11001116
# A stub for the opener argument to built-in open()
11011117
return self._accessor.open(self, flags, mode)
11021118

1103-
def _raw_open(self, flags, mode=0o777):
1104-
"""
1105-
Open the file pointed by this path and return a file descriptor,
1106-
as os.open() does.
1107-
"""
1108-
return self._accessor.open(self, flags, mode)
1109-
11101119
# Public API
11111120

11121121
@classmethod
@@ -1283,22 +1292,7 @@ def touch(self, mode=0o666, exist_ok=True):
12831292
"""
12841293
Create this file with the given access mode, if it doesn't exist.
12851294
"""
1286-
if exist_ok:
1287-
# First try to bump modification time
1288-
# Implementation note: GNU touch uses the UTIME_NOW option of
1289-
# the utimensat() / futimens() functions.
1290-
try:
1291-
self._accessor.utime(self, None)
1292-
except OSError:
1293-
# Avoid exception chaining
1294-
pass
1295-
else:
1296-
return
1297-
flags = os.O_CREAT | os.O_WRONLY
1298-
if not exist_ok:
1299-
flags |= os.O_EXCL
1300-
fd = self._raw_open(flags, mode)
1301-
os.close(fd)
1295+
self._accessor.touch(self, mode, exist_ok)
13021296

13031297
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
13041298
"""

0 commit comments

Comments
 (0)