]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-110109: pathlib ABCs: drop use of `io.text_encoding()` (#113417)
authorBarney Gale <barney.gale@gmail.com>
Wed, 27 Dec 2023 15:32:35 +0000 (15:32 +0000)
committerGitHub <noreply@github.com>
Wed, 27 Dec 2023 15:32:35 +0000 (15:32 +0000)
Do not use the locale-specific default encoding in `PathBase.read_text()`
and `write_text()`. Locale settings shouldn't influence the operation of
these base classes, which are intended mostly for implementing rich paths
on *nonlocal* filesystems.

Lib/pathlib/__init__.py
Lib/pathlib/_abc.py

index bfd2a9249797466d69d8f701ef81a85a7458099c..ab87b49d0277f33242bb822c54a62b009917596e 100644 (file)
@@ -270,6 +270,24 @@ class Path(_abc.PathBase, PurePath):
             encoding = io.text_encoding(encoding)
         return io.open(self, mode, buffering, encoding, errors, newline)
 
+    def read_text(self, encoding=None, errors=None, newline=None):
+        """
+        Open the file in text mode, read it, and close the file.
+        """
+        # Call io.text_encoding() here to ensure any warning is raised at an
+        # appropriate stack level.
+        encoding = io.text_encoding(encoding)
+        return _abc.PathBase.read_text(self, encoding, errors, newline)
+
+    def write_text(self, data, encoding=None, errors=None, newline=None):
+        """
+        Open the file in text mode, write to it, and close the file.
+        """
+        # Call io.text_encoding() here to ensure any warning is raised at an
+        # appropriate stack level.
+        encoding = io.text_encoding(encoding)
+        return _abc.PathBase.write_text(self, data, encoding, errors, newline)
+
     def iterdir(self):
         """Yield path objects of the directory contents.
 
index 43e2670c4d0258be788a4da81ffc1e017090ef99..cfd59ece24673c1cfb7cf9f10768df12b4d60912 100644 (file)
@@ -1,5 +1,4 @@
 import functools
-import io
 import ntpath
 import posixpath
 import sys
@@ -755,7 +754,6 @@ class PathBase(PurePathBase):
         """
         Open the file in text mode, read it, and close the file.
         """
-        encoding = io.text_encoding(encoding)
         with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
             return f.read()
 
@@ -775,7 +773,6 @@ class PathBase(PurePathBase):
         if not isinstance(data, str):
             raise TypeError('data must be str, not %s' %
                             data.__class__.__name__)
-        encoding = io.text_encoding(encoding)
         with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
             return f.write(data)