bpo-29800: Fix crashes in partial.__repr__ if the keys of partial.keywords are not strings (#649) (#672)

This commit is contained in:
Michael Seifert 2017-03-15 08:42:30 +01:00 committed by Serhiy Storchaka
parent 59883bb252
commit 0641ada9b7
4 changed files with 34 additions and 1 deletions

View file

@ -387,6 +387,32 @@ class TestPartialC(TestPartial, unittest.TestCase):
self.assertRaises(TypeError, f.__setstate__, BadSequence())
def test_manually_adding_non_string_keyword(self):
p = self.partial(capture)
# Adding a non-string/unicode keyword to partial kwargs
p.keywords[1234] = 'value'
r = repr(p)
self.assertIn('1234', r)
self.assertIn("'value'", r)
with self.assertRaises(TypeError):
p()
def test_keystr_replaces_value(self):
p = self.partial(capture)
class MutatesYourDict(object):
def __str__(self):
p.keywords[self] = ['sth2']
return 'astr'
# Raplacing the value during key formatting should keep the original
# value alive (at least long enough).
p.keywords[MutatesYourDict()] = ['sth']
r = repr(p)
self.assertIn('astr', r)
self.assertIn("['sth']", r)
class TestPartialPy(TestPartial, unittest.TestCase):
partial = staticmethod(py_functools.partial)

View file

@ -1348,6 +1348,7 @@ Federico Schwindt
Barry Scott
Steven Scott
Nick Seidenman
Michael Seifert
Žiga Seilnacht
Yury Selivanov
Fred Sells

View file

@ -43,6 +43,9 @@ Extension Modules
Library
-------
- bpo-29800: Fix crashes in partial.__repr__ if the keys of partial.keywords
are not strings. Patch by Michael Seifert.
- bpo-29742: get_extra_info() raises exception if get called on closed ssl transport.
Patch by Nikolay Kim.

View file

@ -234,8 +234,11 @@ partial_repr(partialobject *pto)
/* Pack keyword arguments */
assert (PyDict_Check(pto->kw));
for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
Py_SETREF(arglist, PyUnicode_FromFormat("%U, %U=%R", arglist,
/* Prevent key.__str__ from deleting the value. */
Py_INCREF(value);
Py_SETREF(arglist, PyUnicode_FromFormat("%U, %S=%R", arglist,
key, value));
Py_DECREF(value);
if (arglist == NULL)
goto done;
}