[Python-checkins] bpo-39895: Move `pathlib.Path.touch()` implementation into the path accessor. (GH-18838)

zooba webhook-mailer at python.org
Tue Apr 6 20:25:42 EDT 2021


https://github.com/python/cpython/commit/986da8effcd2e9e9334ae016928ef795fb93c373
commit: 986da8effcd2e9e9334ae016928ef795fb93c373
branch: master
author: Barney Gale <barney.gale at gmail.com>
committer: zooba <steve.dower at microsoft.com>
date: 2021-04-07T01:25:37+01:00
summary:

bpo-39895: Move `pathlib.Path.touch()` implementation into the path accessor. (GH-18838)

files:
M Lib/pathlib.py

diff --git a/Lib/pathlib.py b/Lib/pathlib.py
index 64f5f181ed995..cd5884d87d520 100644
--- a/Lib/pathlib.py
+++ b/Lib/pathlib.py
@@ -431,7 +431,23 @@ def link(self, src, dst):
         def symlink(self, src, dst, target_is_directory=False):
             raise NotImplementedError("os.symlink() not available on this system")
 
-    utime = os.utime
+    def touch(self, path, mode=0o666, exist_ok=True):
+        if exist_ok:
+            # First try to bump modification time
+            # Implementation note: GNU touch uses the UTIME_NOW option of
+            # the utimensat() / futimens() functions.
+            try:
+                os.utime(path, None)
+            except OSError:
+                # Avoid exception chaining
+                pass
+            else:
+                return
+        flags = os.O_CREAT | os.O_WRONLY
+        if not exist_ok:
+            flags |= os.O_EXCL
+        fd = os.open(path, flags, mode)
+        os.close(fd)
 
     if hasattr(os, "readlink"):
         readlink = os.readlink
@@ -1100,13 +1116,6 @@ def _opener(self, name, flags, mode=0o666):
         # A stub for the opener argument to built-in open()
         return self._accessor.open(self, flags, mode)
 
-    def _raw_open(self, flags, mode=0o777):
-        """
-        Open the file pointed by this path and return a file descriptor,
-        as os.open() does.
-        """
-        return self._accessor.open(self, flags, mode)
-
     # Public API
 
     @classmethod
@@ -1283,22 +1292,7 @@ def touch(self, mode=0o666, exist_ok=True):
         """
         Create this file with the given access mode, if it doesn't exist.
         """
-        if exist_ok:
-            # First try to bump modification time
-            # Implementation note: GNU touch uses the UTIME_NOW option of
-            # the utimensat() / futimens() functions.
-            try:
-                self._accessor.utime(self, None)
-            except OSError:
-                # Avoid exception chaining
-                pass
-            else:
-                return
-        flags = os.O_CREAT | os.O_WRONLY
-        if not exist_ok:
-            flags |= os.O_EXCL
-        fd = self._raw_open(flags, mode)
-        os.close(fd)
+        self._accessor.touch(self, mode, exist_ok)
 
     def mkdir(self, mode=0o777, parents=False, exist_ok=False):
         """



More information about the Python-checkins mailing list