Skip to content

Commit eebd2c0

Browse files
author
Tomas Correia
committed
Fix: Add update method to SimpleNamespace
1 parent d016763 commit eebd2c0

File tree

1 file changed

+38
-24
lines changed

1 file changed

+38
-24
lines changed

Objects/namespaceobject.c

Lines changed: 38 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -246,17 +246,51 @@ namespace_replace(PyObject *self, PyObject *args, PyObject *kwargs)
246246
}
247247

248248
static PyObject *namespace_update(PyObject *self, PyObject *args, PyObject *kwds);
249+
static PyObject *
250+
namespace_update(PyObject *self, PyObject *args, PyObject *kwargs)
251+
{
252+
PyObject *update_obj = NULL;
253+
254+
if (!PyArg_UnpackTuple(args, "update", 0, 1, &update_obj)) {
255+
return NULL;
256+
}
257+
258+
_PyNamespaceObject *ns = (_PyNamespaceObject *)self;
259+
PyObject *dict = ns->ns_dict;
260+
Py_INCREF(dict);
261+
262+
if (update_obj != NULL) {
263+
if (PyDict_Update(dict, update_obj) < 0) {
264+
Py_DECREF(dict);
265+
return NULL;
266+
}
267+
}
268+
269+
if (kwargs && PyDict_Update(dict, kwargs) < 0) {
270+
Py_DECREF(dict);
271+
return NULL;
272+
}
273+
274+
Py_DECREF(dict);
275+
Py_RETURN_NONE;
276+
}
277+
278+
249279

250280
static PyMethodDef namespace_methods[] = {
251281
{"__reduce__", namespace_reduce, METH_NOARGS,
252282
namespace_reduce__doc__},
253283
{"__replace__", _PyCFunction_CAST(namespace_replace), METH_VARARGS|METH_KEYWORDS,
254284
PyDoc_STR("__replace__($self, /, **changes)\n--\n\n"
255285
"Return a copy of the namespace object with new values for the specified attributes.")},
256-
{"update", (PyCFunction)(void(*)(void))namespace_update,
257-
METH_VARARGS | METH_KEYWORDS,
258-
PyDoc_STR("update(**kwargs)\n--\n\nUpdate namespace attributes from keyword arguments.")
259-
},
286+
287+
{"update", (PyCFunction)(PyCFunctionWithKeywords)namespace_update, METH_VARARGS | METH_KEYWORDS,
288+
PyDoc_STR("update(self, mapping=(), /, **kwargs)\n--\n\n"
289+
"Update the namespace with the given keyword arguments.")},
290+
291+
{NULL, NULL} /* sentinel */
292+
293+
260294

261295
};
262296

@@ -327,27 +361,7 @@ _PyNamespace_New(PyObject *kwds)
327361
return (PyObject *)ns;
328362
}
329363

330-
#include "Python.h"
331-
332-
static PyObject *
333-
namespace_update(PyObject *self, PyObject *args, PyObject *kwds)
334-
{
335-
if (kwds == NULL) {
336-
Py_RETURN_NONE;
337-
}
338-
339-
PyObject *dict = PyObject_GetAttrString(self, "__dict__");
340-
if (dict == NULL) {
341-
return NULL;
342-
}
343364

344-
int result = PyDict_Update(dict, kwds);
345-
Py_DECREF(dict);
346365

347-
if (result < 0) {
348-
return NULL;
349-
}
350366

351-
Py_RETURN_NONE;
352-
}
353367

0 commit comments

Comments
 (0)