Skip to content

Commit d716ea3

Browse files
authored
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.
1 parent fbfb0e1 commit d716ea3

File tree

3 files changed

+12
-0
lines changed

3 files changed

+12
-0
lines changed

Lib/pathlib/_os.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,12 @@ def magic_open(path, mode='r', buffering=-1, encoding=None, errors=None,
186186
pass
187187
else:
188188
return attr(path, buffering, encoding, errors, newline)
189+
elif encoding is not None:
190+
raise ValueError("binary mode doesn't take an encoding argument")
191+
elif errors is not None:
192+
raise ValueError("binary mode doesn't take an errors argument")
193+
elif newline is not None:
194+
raise ValueError("binary mode doesn't take a newline argument")
189195

190196
try:
191197
attr = getattr(cls, f'__open_{mode}b__')

Lib/test/test_pathlib/test_read.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@ def test_open_rb(self):
3939
p = self.root / 'fileA'
4040
with magic_open(p, 'rb') as f:
4141
self.assertEqual(f.read(), b'this is file A\n')
42+
self.assertRaises(ValueError, magic_open, p, 'rb', encoding='utf8')
43+
self.assertRaises(ValueError, magic_open, p, 'rb', errors='strict')
44+
self.assertRaises(ValueError, magic_open, p, 'rb', newline='')
4245

4346
def test_read_bytes(self):
4447
p = self.root / 'fileA'

Lib/test/test_pathlib/test_write.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ def test_open_wb(self):
4141
#self.assertIsInstance(f, io.BufferedWriter)
4242
f.write(b'this is file A\n')
4343
self.assertEqual(self.ground.readbytes(p), b'this is file A\n')
44+
self.assertRaises(ValueError, magic_open, p, 'wb', encoding='utf8')
45+
self.assertRaises(ValueError, magic_open, p, 'wb', errors='strict')
46+
self.assertRaises(ValueError, magic_open, p, 'wb', newline='')
4447

4548
def test_write_bytes(self):
4649
p = self.root / 'fileA'

0 commit comments

Comments
 (0)