https://github.com/python/cpython/commit/d716ea34cb8a105e8e39a1ddfd610c3c0f11a0e7
commit: d716ea34cb8a105e8e39a1ddfd610c3c0f11a0e7
branch: main
author: Barney Gale <[email protected]>
committer: barneygale <[email protected]>
date: 2025-03-24T15:13:18Z
summary:
GH-128520: pathlib ABCs: validate `magic_open()` arguments (#131617)
When `pathlib._os.magic_open()` is called to open a path in binary mode,
raise `ValueError` if any of the *encoding*, *errors* or *newline*
arguments are given. This matches the `open()` built-in.
files:
M Lib/pathlib/_os.py
M Lib/test/test_pathlib/test_read.py
M Lib/test/test_pathlib/test_write.py
diff --git a/Lib/pathlib/_os.py b/Lib/pathlib/_os.py
index ee8657f427efbd..e3751bbcb62377 100644
--- a/Lib/pathlib/_os.py
+++ b/Lib/pathlib/_os.py
@@ -186,6 +186,12 @@ def magic_open(path, mode='r', buffering=-1,
encoding=None, errors=None,
pass
else:
return attr(path, buffering, encoding, errors, newline)
+ elif encoding is not None:
+ raise ValueError("binary mode doesn't take an encoding argument")
+ elif errors is not None:
+ raise ValueError("binary mode doesn't take an errors argument")
+ elif newline is not None:
+ raise ValueError("binary mode doesn't take a newline argument")
try:
attr = getattr(cls, f'__open_{mode}b__')
diff --git a/Lib/test/test_pathlib/test_read.py
b/Lib/test/test_pathlib/test_read.py
index 1a14649fafee80..753ae5d760aceb 100644
--- a/Lib/test/test_pathlib/test_read.py
+++ b/Lib/test/test_pathlib/test_read.py
@@ -39,6 +39,9 @@ def test_open_rb(self):
p = self.root / 'fileA'
with magic_open(p, 'rb') as f:
self.assertEqual(f.read(), b'this is file A\n')
+ self.assertRaises(ValueError, magic_open, p, 'rb', encoding='utf8')
+ self.assertRaises(ValueError, magic_open, p, 'rb', errors='strict')
+ self.assertRaises(ValueError, magic_open, p, 'rb', newline='')
def test_read_bytes(self):
p = self.root / 'fileA'
diff --git a/Lib/test/test_pathlib/test_write.py
b/Lib/test/test_pathlib/test_write.py
index 040af7be152fc2..d302e0a9caa889 100644
--- a/Lib/test/test_pathlib/test_write.py
+++ b/Lib/test/test_pathlib/test_write.py
@@ -41,6 +41,9 @@ def test_open_wb(self):
#self.assertIsInstance(f, io.BufferedWriter)
f.write(b'this is file A\n')
self.assertEqual(self.ground.readbytes(p), b'this is file A\n')
+ self.assertRaises(ValueError, magic_open, p, 'wb', encoding='utf8')
+ self.assertRaises(ValueError, magic_open, p, 'wb', errors='strict')
+ self.assertRaises(ValueError, magic_open, p, 'wb', newline='')
def test_write_bytes(self):
p = self.root / 'fileA'
_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]