Skip to content

Commit 5003a53

Browse files
gh-155733: Validate string keys in partial.__setstate__
1 parent c3a2dfa commit 5003a53

3 files changed

Lines changed: 16 additions & 0 deletions

File tree

Lib/functools.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,9 @@ def __setstate__(self, state):
417417
(namespace is not None and not isinstance(namespace, dict))):
418418
raise TypeError("invalid partial state")
419419

420+
if kwds is not None and any(not isinstance(k, str) for k in kwds):
421+
raise TypeError("keywords must be strings")
422+
420423
if args and args[-1] is Placeholder:
421424
raise TypeError("trailing Placeholders are not allowed")
422425
phcount, merger = _partial_prepare_merger(args)

Lib/test/test_functools.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,9 @@ def test_non_string_keywords(self):
167167
p.keywords[1] = 'x'
168168
with self.assertRaisesRegex(TypeError, "keywords must be strings"):
169169
p()
170+
p2 = self.partial(capture)
171+
with self.assertRaisesRegex(TypeError, "keywords must be strings"):
172+
p2.__setstate__((capture, (), {1: 'x'}, None))
170173

171174
def test_no_side_effects(self):
172175
# make sure there are no side effects that affect subsequent calls

Modules/_functoolsmodule.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,16 @@ partial_setstate(PyObject *self, PyObject *state)
830830
PyErr_SetString(PyExc_TypeError, "invalid partial state");
831831
return NULL;
832832
}
833+
if (kw != Py_None) {
834+
Py_ssize_t pos = 0;
835+
PyObject *key, *val;
836+
while (PyDict_Next(kw, &pos, &key, &val)) {
837+
if (!PyUnicode_Check(key)) {
838+
PyErr_SetString(PyExc_TypeError, "keywords must be strings");
839+
return NULL;
840+
}
841+
}
842+
}
833843

834844
Py_ssize_t nargs = PyTuple_GET_SIZE(fnargs);
835845
if (nargs && PyTuple_GET_ITEM(fnargs, nargs - 1) == pto->placeholder) {

0 commit comments

Comments
 (0)