From: Serhiy Storchaka Date: Mon, 20 Feb 2017 12:04:30 +0000 (+0200) Subject: bpo-29532: Altering a kwarg dictionary passed to functools.partial() (#190) X-Git-Tag: v3.7.0a1~1316 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=9639e4ab6d5bd3ca0ab34fef127e9fc84b6b88b9;p=python bpo-29532: Altering a kwarg dictionary passed to functools.partial() (#190) no longer affects a partial object after creation. --- diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index 63fe83e5db..612ca17a60 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -90,6 +90,15 @@ class TestPartial: p(b=7) self.assertEqual(d, {'a':3}) + def test_kwargs_copy(self): + # Issue #29532: Altering a kwarg dictionary passed to a constructor + # should not affect a partial object after creation + d = {'a': 3} + p = self.partial(capture, **d) + self.assertEqual(p(), ((), {'a': 3})) + d['a'] = 5 + self.assertEqual(p(), ((), {'a': 3})) + def test_arg_combinations(self): # exercise special code paths for zero args in either partial # object or the caller diff --git a/Misc/NEWS b/Misc/NEWS index 0c2a5730e3..fa7e3f5a5e 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -232,6 +232,9 @@ Extension Modules Library ------- +- bpo-29532: Altering a kwarg dictionary passed to functools.partial() + no longer affects a partial object after creation. + - bpo-22807: Add uuid.SafeUUID and uuid.UUID.is_safe to relay information from the platform about whether generated UUIDs are generated with a multiprocessing safe method. diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c index 4170883368..c8565054c9 100644 --- a/Modules/_functoolsmodule.c +++ b/Modules/_functoolsmodule.c @@ -88,10 +88,13 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw) if (kw == NULL) { pto->kw = PyDict_New(); } - else { + else if (Py_REFCNT(kw) == 1) { Py_INCREF(kw); pto->kw = kw; } + else { + pto->kw = PyDict_Copy(kw); + } } else { pto->kw = PyDict_Copy(pkw);