Skip to content

Commit

Permalink
pythongh-122888: Fix crash on certain calls to str()
Browse files Browse the repository at this point in the history
  • Loading branch information
JelleZijlstra committed Aug 10, 2024
1 parent 5580f31 commit 6624420
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Lib/test/test_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -1747,6 +1747,16 @@ def test_constructor_keyword_args(self):
self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
self.assertEqual(str(object=b'foo', errors='strict'), 'foo')

def test_constructor_errors(self):
with self.assertRaises(TypeError):
str(b"x", b"ascii")
with self.assertRaises(TypeError):
str(b"x", encoding=b"ascii")
with self.assertRaises(TypeError):
str(b"x", "ascii", b"strict")
with self.assertRaises(TypeError):
str(b"x", "ascii", errors=b"strict")

def test_constructor_defaults(self):
"""Check the constructor argument defaults."""
# The object argument defaults to '' or b''.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash on certain calls to ``str()`` with positional arguments of the
wrong type. Patch by Jelle Zijlstra.
11 changes: 10 additions & 1 deletion Objects/unicodeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -15121,7 +15121,16 @@ unicode_vectorcall(PyObject *type, PyObject *const *args,
return PyObject_Str(object);
}
const char *encoding = arg_as_utf8(args[1], "encoding");
const char *errors = (nargs == 3) ? arg_as_utf8(args[2], "errors") : NULL;
if (encoding == NULL) {
return NULL;
}
const char *errors = NULL;
if (nargs == 3) {
errors = arg_as_utf8(args[2], "errors");
if (errors == NULL) {
return NULL;
}
}
return PyUnicode_FromEncodedObject(object, encoding, errors);
}

Expand Down

0 comments on commit 6624420

Please sign in to comment.