Skip to content

Commit b08ec58

Browse files
barneygaleaisk
authored andcommitted
pythonGH-110109: pathlib ABCs: drop use of io.text_encoding() (python#113417)
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.
1 parent a5690c3 commit b08ec58

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

Lib/pathlib/__init__.py

+18
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,24 @@ def open(self, mode='r', buffering=-1, encoding=None,
270270
encoding = io.text_encoding(encoding)
271271
return io.open(self, mode, buffering, encoding, errors, newline)
272272

273+
def read_text(self, encoding=None, errors=None, newline=None):
274+
"""
275+
Open the file in text mode, read it, and close the file.
276+
"""
277+
# Call io.text_encoding() here to ensure any warning is raised at an
278+
# appropriate stack level.
279+
encoding = io.text_encoding(encoding)
280+
return _abc.PathBase.read_text(self, encoding, errors, newline)
281+
282+
def write_text(self, data, encoding=None, errors=None, newline=None):
283+
"""
284+
Open the file in text mode, write to it, and close the file.
285+
"""
286+
# Call io.text_encoding() here to ensure any warning is raised at an
287+
# appropriate stack level.
288+
encoding = io.text_encoding(encoding)
289+
return _abc.PathBase.write_text(self, data, encoding, errors, newline)
290+
273291
def iterdir(self):
274292
"""Yield path objects of the directory contents.
275293

Lib/pathlib/_abc.py

-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import functools
2-
import io
32
import ntpath
43
import posixpath
54
import sys
@@ -755,7 +754,6 @@ def read_text(self, encoding=None, errors=None, newline=None):
755754
"""
756755
Open the file in text mode, read it, and close the file.
757756
"""
758-
encoding = io.text_encoding(encoding)
759757
with self.open(mode='r', encoding=encoding, errors=errors, newline=newline) as f:
760758
return f.read()
761759

@@ -775,7 +773,6 @@ def write_text(self, data, encoding=None, errors=None, newline=None):
775773
if not isinstance(data, str):
776774
raise TypeError('data must be str, not %s' %
777775
data.__class__.__name__)
778-
encoding = io.text_encoding(encoding)
779776
with self.open(mode='w', encoding=encoding, errors=errors, newline=newline) as f:
780777
return f.write(data)
781778

0 commit comments

Comments
 (0)