Skip to content

GH-128520: pathlib ABCs: validate magic_open() arguments #131617

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Lib/pathlib/_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__')
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_pathlib/test_read.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_pathlib/test_write.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Loading