Skip to content

Commit 4774946

Browse files
committed
#15180: Clarify posixpath.join() error message when mixing str & bytes
1 parent a3d1cac commit 4774946

3 files changed

Lines changed: 24 additions & 8 deletions

File tree

Lib/posixpath.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,20 @@ def join(a, *p):
7474
will be discarded."""
7575
sep = _get_sep(a)
7676
path = a
77-
for b in p:
78-
if b.startswith(sep):
79-
path = b
80-
elif not path or path.endswith(sep):
81-
path += b
77+
try:
78+
for b in p:
79+
if b.startswith(sep):
80+
path = b
81+
elif not path or path.endswith(sep):
82+
path += b
83+
else:
84+
path += sep + b
85+
except TypeError:
86+
strs = [isinstance(s, str) for s in (a, ) + p]
87+
if any(strs) and not all(strs):
88+
raise TypeError("Can't mix strings and bytes in path components.")
8289
else:
83-
path += sep + b
90+
raise
8491
return path
8592

8693

Lib/test/test_posixpath.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,15 @@ def test_join(self):
5656
self.assertEqual(posixpath.join(b"/foo/", b"bar/", b"baz/"),
5757
b"/foo/bar/baz/")
5858

59-
self.assertRaises(TypeError, posixpath.join, b"bytes", "str")
60-
self.assertRaises(TypeError, posixpath.join, "str", b"bytes")
59+
with self.assertRaises(TypeError) as e:
60+
posixpath.join(b'bytes', 'str')
61+
self.assertIn("Can't mix strings and bytes", e.args[0])
62+
with self.assertRaises(TypeError) as e:
63+
posixpath.join('str', b'bytes')
64+
self.assertIn("Can't mix strings and bytes", e.args[0])
65+
with self.assertRaises(TypeError) as e:
66+
posixpath.join('str', bytearray(b'bytes'))
67+
self.assertIn("Can't mix strings and bytes", e.args[0])
6168

6269
def test_split(self):
6370
self.assertEqual(posixpath.split("/foo/bar"), ("/foo", "bar"))

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ Core and Builtins
8787
Library
8888
-------
8989

90+
- Issue #15180: Clarify posixpath.join() error message when mixing str & bytes
91+
9092
- Issue #15230: runpy.run_path now correctly sets __package__ as described
9193
in the documentation
9294

0 commit comments

Comments
 (0)